【发布时间】:2012-08-16 18:03:08
【问题描述】:
我有一个名为 Purchase 的模型,其中包含一个名为 tickets 和 amount 的字段。这个模型属于Event,它是有价格的。我想在创建新的 Purchase 后调用 update_amount 回调,但在回调方法中关联的事件似乎不存在。
class Purchase < ActiveRecord::Base
belongs_to :event
attr_accessible :event_id, :tickets, :amount
delegate :price, to: :event
after_initialize :update_amount
...
def update_amount
update_attribute :amount, self.tickets * self.price
end
end
class Event < ActiveRecord::Base
attr_accessible :price
...
end
但是,当我测试它时,我遇到了以下问题:
$ Purchase.new(tickets: 2, event_id: 1541)
RuntimeError: Purchase#price delegated to event.price, but event is nil: <Purchase
id: nil, user_id: nil, event_id: nil, amount: nil, tickets: 1,
event_date: nil, created_at: nil, updated_at: nil, checkout_id: nil,
checkout_uri: nil, state: "incomplete">
请注意,系统中有一个 id 为 1541 的事件,但 ActiveRecord 无权访问它?我在没有委托的情况下使用 event.price 尝试了同样的事情,但同样的事情发生了,即 NilClass 错误找不到价格。
谁能帮我理解这一点? after_initialize 块中没有形成关联吗?有什么我忽略的吗?
PS:我最终在回调中添加了一个守卫,因此如果 Event 为 nil,它就不会被调用。不过,这只是一个 hack,如果能找到这个问题的根源,那就太好了。
【问题讨论】:
-
您找到解决方案了吗?我现在正在处理类似的问题。
标签: ruby-on-rails activerecord callback