I am following the Agile Web Development book tutorial with some small changes, halfway through Chapter 12 on Check Out.
I am getting the following error:
NoMethodError (undefined method `price=' for #<LineItem:0x00000103a0de18>):
app/models/cart.rb:11:in `add_deal'
app/controllers/line_items_controller.rb:45:in `create'
Here is my cart model:
class Cart < ActiveRecord::Base
# attr_accessible :title, :body
has_many :line_items, dependent: :destroy
def add_deal(deal_id)
current_item = line_items.find_by_deal_id(deal_id)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(deal_id: deal_id)
current_item.price = current_item.deal.price
end
current_item
end
def total_price
line_items.to_a.sum { |item| item.total_price }
end
end
Here is my create action in line_items_controller with the relevant line 45 where it freezes:
def create
@cart = current_cart
deal = Deal.find(params[:deal_id])
@line_item = @cart.add_deal(deal.id)
My line item model:
class LineItem < ActiveRecord::Base
attr_accessible :cart_id, :deal_id, :quantity
belongs_to :order
belongs_to :deal
belongs_to :cart
def total_price
deal.price * quantity
end
end
Here is my deal model:
class Deal < ActiveRecord::Base
attr_accessible :description, :expiration, :featured, :image_url, :inventory, :price, :sold, :title, :value, :deal_id
has_many :line_items
before_destroy :ensure_not_referenced_by_any_line_item
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :title, :description, :image_url, presence: true
private
# ensure that there are no line items referencing this product
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'Line Items present')
return false
end
end
end
When I tried using the console, item.deal.price works just fine but not item.price.
In the line_item model, I tried attr_accessible :price but it did fix anything.
I checked my code vs the book and I can’t tell any significant difference at all.
One idea is to set a database field for price for LineItems but the book doesn’t do that and it violates the DRY principle.
Any help would be greatly appreciated as I’ve stared at the source code for hours and can’t find anything wrong. Thanks.
You were distracted during reading the book.
LineItemmodel does contain thepricefield. This totally complies with DRY principle, as there is a possibility of changing a price of aProductin the future andLineItemmodel shows as a history of deals.