2012-04-16 66 views
1

我正在关注敏捷Web开发书籍教程,其中有一些小的更改,在第12章“签出”的中途。使用敏捷书籍的line_item中的Rails 3.2 NoMethodError(undefined method` price =')

我收到以下错误:

NoMethodError (undefined method `price=' for #<LineItem:0x00000103a0de18>): 
app/models/cart.rb:11:in `add_deal' 
app/controllers/line_items_controller.rb:45:in `create' 

这里是我的购物车型号:

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 

这是我创造line_items_controller与它冻结了相关线路45行动:

def create 
    @cart = current_cart 
    deal = Deal.find(params[:deal_id]) 
    @line_item = @cart.add_deal(deal.id) 

我的订单项型号:

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 

这里是我的交易模式:

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 

当我试图使用控制台,item.deal.price工作得很好,但不是item.price。

在line_item模型中,我尝试了attr_accessible:price,但它确实解决了所有问题。

我检查了我的代码和书本,我根本看不出任何明显的区别。

一个想法是为LineItems的价格设置一个数据库字段,但该书没有这样做,并且违反了DRY原则。

任何帮助将不胜感激,因为我盯着源代码几个小时,无法找到任何错误。谢谢。

回答

0

在阅读本书时,你分心了。 LineItem模型确实包含price字段。这完全符合DRY原则,因为未来有可能改变Product的价格,LineItem模型显示为交易历史。

+0

谢谢!希望我早些时候问过,但是更好地理解DRY。 – Castielle 2012-04-16 17:23:10

+0

你看过本书的图5.3吗?我犹豫了,因为我不确定它是否合法。 – jdoe 2012-04-16 17:25:31

+0

好的 - 这些图纸有助于理解。虽然我认为这本书中有一个错字,因为没有任何地方的移植列表。 – Castielle 2012-04-16 18:06:38

相关问题