2012-04-16 64 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

相關問題