【问题标题】:Rails 3.2 NoMethodError (undefined method `price=') in line_item using Agile bookRails 3.2 NoMethodError (undefined method `price=') in line_item 使用敏捷书
【发布时间】:2012-04-16 16:26:06
【问题描述】:

我正在关注敏捷 Web 开发书籍教程,并进行了一些小改动,第 12 章的检查已过半。

我收到以下错误:

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 原则。

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

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

    【讨论】:

    • 谢谢!希望我早点问过,但更好地了解 DRY。
    • 看书的图5.3了吗?由于不确定是否合法,因此我犹豫是否在此处发布。
    • 嗯,好的——这些图有助于理解。虽然我确实认为书中有一个错字,因为任何地方都没有列出迁移。
    • 本书源码在这里:pragprog.com/titles/rails4/source_code
    • 好建议 - “阅读源代码,卢克” :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 2022-11-20
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多