I’m working with the Agile Web Development with Rails (4th edition) book and I bumped into a piece of code that is not working. I tried hard to figure out why it’s not working, but I didn’t make it.
BACKGROUD INFORMATION
The following classes are involved:
class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
end
class LineItem < ActiveRecord::Base
belongs_to :product
belongs_to :cart
end
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
end
end
NOW
here is where it fails:
class LineItemsController < ApplicationController
def index
@line_items = LineItem.all`
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @line_items }
end
end
# GET /line_items/1
# GET /line_items/1.xml
def show
@line_item = LineItem.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @line_item }
end
end
# GET /line_items/new
# GET /line_items/new.xml
def new
@line_item = LineItem.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @line_item }
end
end
# GET /line_items/1/edit
def edit
@line_item = LineItem.find(params[:id])
end
# POST /line_items
# POST /line_items.xml
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = **@cart.line_items.build(:product => product)**`
ERROR MESSAGE
*NoMethodError in LineItemsController#create
undefined method `line_items’ for 9:Fixnum
Rails.root: /home/tmiskiew/depot*
*app/controllers/line_items_controller.rb:53:in `create’
Request
Parameters:
{“product_id”=>”4”,
“authenticity_token”=>”dR4nL5zI+R7qIIPwNkl3EoaI1KyFWRokvh92m3PwD8o=”}*
Anyone an idea what’s wrong with @cart.line_items.build?
I’m working rails 3.0.9 and ruby 1.8.7
Thanks
Thomas
Have a look at your error
undefined method line_items' for 9:FixnumThis says that @cart is a number, not an Cart object (
@cart = current_cartfrom create action returns a number),current_cartfunction returns a number becauseCart.find(session[:cart_id]) returns
recordNotFoundand yourrescueblock fromcurrent_cartfunction will be executed.Remember that every function in Ruby returns the result of the last executed line, so you will get returned the cart.id
Edit: For first comment, try to rewrite method
def current_cart Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound cart = Cart.create session[:cart_id] = cart.id cart # this will get returned end end