Show page, show associations - ruby

i try to find out how i can show associations deeper than one level.
Show at my FORM, i just done it there:
form do |f|
f.inputs "Details" do
f.input :name
f.input :item_category
f.input :resource
f.input :status
end
f.inputs "Actions" do
f.semantic_errors *f.object.errors.keys
f.has_many :item_actions, :allow_destroy => true, :heading => 'Planets', :new_record => true do |obj|
obj.input :action
obj.input :status
obj.input :_destroy, :as=>:boolean, :required => false, :label=>'Remove'
obj.has_many :item_action_skills, :heading => "Skills" do |ias|
ias.input :skill
ias.input :level
end
end
end
f.actions
end
You can see, i show has_many :item_actions and going one level deeper to item_action.item_action_skills. On this form is works perfect.
Now i'll want it on the show page too. My code:
show do |obj|
attributes_table do
row :name
row :item_category
row(:resource) {|obj| status_tag((obj.resource ? 'yes' : 'no'), (obj.resource ? :ok : :error))}
row(:status) {|obj| status_tag(obj.status_string.first, obj.status_string.last) }
end
panel "Actions" do
table_for obj.item_actions do
column :action
column(:status) {|obj| status_tag(obj.status_string.first, obj.status_string.last) }
end
end
active_admin_comments
end
I write table_for, but how to go now to the next association?
I want the item_action.item_action_skills.
I have no idea. Any idea?
Thanks!
Ruby 1.9.3
Rails 3.2.14
ActiveAdmin 0.6.0

Try this:
panel "Actions" do
table_for obj.item_actions do
column :action
column(:status) {|obj| status_tag(obj.status_string.first, obj.status_string.last) }
column("skills"){|resource|
table_for resource.item_action_skills do
column(:your_column)
end
}
end
end

Related

rollback transaction error rails from google geocoding api

I am trying to create a review form in my rails app but when i click on the submit button, the form cannot be submitted.When i lookup the error in the terminal and i get this error. i searched the error but couldn't find any solution. did anyone had this issue before?:
Google API error: over query limit.
(0.1ms) rollback transaction
Update
I am not only getting the Google API error. sometimes i get this error and other time i only get rollback transaction only.
This is the Reviews Controller:
class ReviewsController < ApplicationController
# check if logged in
before_action :check_login, except: [:index, :show]
def index
# this is our list page for our reviews
#price = params[:price]
#cuisine = params[:cuisine]
#location = params[:location]
# start with all the reviews
#reviews = Review.all
# filtering by price
if #price.present?
#reviews = #reviews.where(price: #price)
end
# filter by cuisine
if #cuisine.present?
#reviews = #reviews.where(cuisine: #cuisine)
end
# search near the location
if #location.present?
#reviews = #reviews.near(#location)
end
end
def new
# the form for adding a new review
#review = Review.new
end
def create
# take info from the form and add it to the model
#review = Review.new(form_params)
# and then associate it with a user
#review.user = #current_user
# we want to check if the model can be saved
# if it is, we're go the home page again
# if it isn't, show the new form
if #review.save
flash[:succces] = "Your review was posted!"
redirect_to root_path
else
# show the view for new.html.erb
render "new"
end
end
def show
# individual review page
#review = Review.find(params[:id])
end
def destroy
# find the individual review
#review = Review.find(params[:id])
# destroy if they have access
if #review.user == #current_user
#review.destroy
end
# redirect to the home page
redirect_to root_path
end
def edit
# find the individual review (to edit)
#review = Review.find(params[:id])
if #review.user != #current_user
redirect_to root_path
elsif #review.created_at < 4.hours.ago
redirect_to review_path(#review)
end
end
def update
# find the individual review
#review = Review.find(params[:id])
if #review.user != #current_user
redirect_to root_path
else
# update with the new info from the form
if #review.update(form_params)
# redirect somewhere new
redirect_to review_path(#review)
else
render "edit"
end
end
end
def form_params
params.require(:review).permit(:title, :restaurant, :body, :score,
:ambiance, :cuisine, :price, :address)
end
end
This is the Review form page:
<%= simple_form_for #review do |f| %>
<%= f.input :title %>
<%= f.input :restaurant %>
<%= f.input :address %>
<%= f.input :body %>
<%= f.input :cuisine %>
<%= f.input :price %>
<%= f.input :score %>
<%= f.input :ambiance %>
<%= f.button :submit %>
<% end %>
The Review Model
class Review < ApplicationRecord
# add an association that has a 1-to-many relationship
has_many :comments
has_many :bookmarks
# add an association to the user
belongs_to :user
geocoded_by :address
after_validation :geocode
validates :title, presence: true
validates :body, length: { minimum: 10 }
validates :score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 10 }
validates :restaurant, presence: true
validates :address, presence: true
def to_param
id.to_s + "-" + title.parameterize
end
end
This is My Schema file
create_table "reviews", force: :cascade do |t|
t.string "title"
t.text "body"
t.integer "score"
t.string "restaurant"
t.integer "price"
t.string "cuisine"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "phone_number"
t.string "ambiance"
t.text "address"
t.float "latitude"
t.float "longitude"
t.integer "user_id"
end
You have two problems:
you are going over Google's Geocoding API quota as evidenced by the error message "over query limit"
Most likely because of that, your model cannot be saved is rolled back. The geocoding API call fails, it doesn't save.
I would check the Google API Console and see if you have actually hit their quota (possible if you're running multiple tests and you're on their free tier of service). If you have not hit the limit, file a support request with Google API.
You probably reached your Google API quota.
In model you have geocoded_by ... that is used by gem geocoder so have a look at that.
Google has per second limit as well as per day limit link

How To Create A Search Function - Ruby On Rails

Im trying to make a search function for an app. I have a service object called searches and all search logic is in this object.
When the search form is submitted with an about query #results in Search Controller is the following array.
=> [
[0] [],
[1] [
[0] About {
:id => 2,
:title => "About",
:slug => "about",
:meta_description => "",
:meta_keywords => "",
:content => "<p>Lorem ipsum about</p>",
:position => 1,
:published => true,
:on_menu => true,
:created_at => Wed, 13 Jan 2016 00:44:08 UTC +00:00,
:updated_at => Fri, 15 Jan 2016 04:05:52 UTC +00:00
}
],
[2] [],
[3] []
]
Here is my Search object. See how the User attributes are different then the Pages and NewsArticle? Good. Now go look at the view.
class SearchService
attr_accessor :query
def initialize(query)
#query = query
end
# searchable_fields_by_model
CONDITIONS_BY_MODEL = {
Page => [:title, :content],
NewsArticle => [:title, :content]
User => [:first_name, :last_name]
}
def raw_results
ActiveRecord::Base.transaction do
CONDITIONS_BY_MODEL.flat_map do |model, fields|
Array(fields).map do |field|
model.where(["#{field} LIKE ?", "%#{query}%"])
end
end
end
end
end
Below is my view. Currently the view will only display content and title. But my User has first_name and last_name therefore it won't display. I need a way to display the results of all Models and it needs to be clean so if i add another model to search with entirely different attributes it will still display. How would you do this?
.page-header
%h1 Search#index
- #results.each do |results|
- results.each do |r|
%p= r.title
%p= r.content
Search controller
class SearchController < ApplicationController
def index
#results = SearchService.new(params[:q]).results
end
end
How to fix this.
class SearchController < ApplicationController
def index
#results = SearchService.new(params[:q]).results
#page_results = []
#news_article_results = []
#category_results = []
#results.each do |resource|
if resource.class == Page
#page_results << resource
elsif resource.class == NewsArticle
#news_article_results << resource
elsif resource.class == Category
#category_results << resource
else
end
end
end
end
class SearchService
MIN_QUERY_LENGTH = 3
attr_accessor :query
def initialize(query)
raise ArgumentError if query.length < MIN_QUERY_LENGTH
#query = query
end
# searchable_fields_by_model
CONDITIONS_BY_MODEL = {
Page => [:title, :content],
NewsArticle => [:title, :content],
Category => :name,
}
def results
#results ||= ActiveRecord::Base.transaction do
CONDITIONS_BY_MODEL.flat_map do |model, fields|
Array(fields).flat_map do |field|
model.where(["#{field} LIKE ?", "%#{query}%"])
end
end
end
end
end
Here is my view
.page-header
%h1 Search Results
%h2= "For #{params[:q]}"
%br
%h2 Pages
- #page_results.each do |resource|
%p= link_to "#{resource.title}", page_path(resource.slug)
= resource.content.html_safe
%h2 News Article
- #news_article_results.each do |resource|
%p= link_to "#{resource.title}", news_article_path(resource.slug)
= resource.content.html_safe
%h2 Category
- #category_results.each do |resource|
%p= link_to "#{resource.name}", category_path(resource.slug)

Rails 4 ActiveModel::MissingAttributeError in OrdersController#create

I m trying to build a shopping cart for a website. I have the cart working so you can add to the cart. The problem I am having is when I try and checkout items in the cart and try to submit my order. I am getting the following error:
ActiveModel::MissingAttributeError in OrdersController#create
along with
can't write unknown attribute `order_id'
The problem is highlighting this piece of code in my orders_controller.rb file
respond_to do |format|
if #order.save
Cart.destroy(session[:cart_id]) session[:cart_id] = nil
I just cant seem to fix this error.
Below is the create method in my orders_controller.rb file
def create
#order = Order.new(order_params)
#order.add_line_items_from_cart(#cart)
respond_to do |format|
if #order.save
Cart.destroy(session[:cart_id])
session[:cart_id] = nil
format.html { redirect_to store_url,
notice: 'Thank you for your order.' }
format.json { render action: 'show', status: :created, location: #order }
else
format.html { render action: 'new' }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
my migration file
class AddOrderToLineItem < ActiveRecord::Migration
def change
add_column :line_items, :order, :reference
end
end
my order.rb model
class Order < ActiveRecord::Base
has_many :line_items, dependent: :destroy
validates :name, :address, :email, presence: true
PAYMENT_TYPES = [ "Check", "Credit card", "Purchase order" ]
validates :pay_type, inclusion: PAYMENT_TYPES
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
end
migration order table
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.string :name
t.text :address
t.string :email
t.string :pay_type
t.timestamps
end
end
end
Ok, I think I see the problem. Your migration for orders in line items probably didn't create the order_id column you expected, it probably created an orders column or something.
Verify that this is the case in the database. If so, undo your previous migration and try this instead:
class AddOrderToLineItem < ActiveRecord::Migration
def change
add_column :line_items, :order_id, :int
end
end
If not, please respond to this answer.

I am having problems with getting current_user data

I am in the activeadmin dashboard. I am trying to only show customers of the current_user but I get an error undefined local variable or methodcurrent_user'`
here is my code for the dashboard:
section "Recent Customers" do
table_for Customer.owned_by(current_user).limit(5) do
column "Name" do |customer|
link_to customer.name, admin_customers_path(customer)
end
column :phone
column :email, :sortable => :email do |customer|
link_to customer.email, "mailto:#{customer.email}"
end
end
strong { link_to "View All Customers", admin_customers_path }
end
in active_admin try current_admin_user

Rails -- before_save not working?

I am following Michael Hartl's RoR tutorial, and it is covering the basics of password encryption. This is the User model as it currently stands:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email,: password, :password_confirmation
email_regex = /^[A-Za-z0-9._+-]+#[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+[A-Za-z]$/
#tests for valid email addresses.
validates :name, :presence => true,
:length => {:maximum => 50}
validates :email, :presence => true,
:format => {:with => email_regex},
:uniqueness => {:case_sensitive => false}
validates :password, :presence => true,
:length => {:maximum => 20, :minimum => 6},
:confirmation => true
before_save :encrypt_password
private
def encrypt_password
#encrypted_password = encrypt(password)
end
def encrypt(string)
string
end
end
(Obviously this isn't doing any encrypting because the encrypt method isn't really implemented but that's not my question)
I then wrote the following Spec (according to the tutorial):
require 'spec_helper'
describe User do
before(:each) do
#attr = { :name => "Example User", :email => "user#example.com",
:password => "abc123", :password_confirmation => "abc123"}
end
describe "password encryption" do
before(:each) do
#user = User.create!(#attr) # we are going to need a valid user in order
# for these tests to run.
end
it "should have an encrypted password attribute" do
#user.should respond_to(:encrypted_password)
end
it "should set the encrypted password upon user creation" do
#user.encrypted_password.should_not be_blank
end
end
end
The first of these tests passes, but since #user.encrypted_password is nil, the second test fails. But I don't understand why it's nil since the encrypt_password method should be being called by before_save. I know I must be missing something -- can someone please explain?
The encrypt_password method is incorrect, it should read:
def encrypt_password
self.encrypted_password = encrypt(password)
end
Note the use of self, which will properly set the attribute for the user object rather than creating an instance variable which is forgotten.
This is an old question and this is more of a comment but I don't have enough reputation to comment yet. Just wanted to link this question too as it goes into some solid detail about self.
Why isn't self always needed in ruby / rails / activerecord?

Resources