我有一个名为Purchase的模型,其中有一个名为tickets和amount的字段。该模型属于Event,具有价格。我想在创建新购买后调用update_amount回调函数,但在回调方法中,关联事件似乎不存在。Rails协会在after_initialize回调中为零
$ 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">
注意,有与编号1541的系统中的事件,但ActiveRecord的不能访问到:
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
当我测试了一下,不过,我碰到下面的来?我在没有委托的情况下尝试了同样的事情,使用event.price,并且发生了同样的事情,即没有找到NilClass错误的价格。
任何人都可以帮助我理解这一点吗?协会是否不在after_initialize
区块中形成?有我忽略的东西吗?
PS:我最终在回调中添加了一个警戒,所以如果Event为零,它就不会被调用。尽管如此,这只是一个骇客,而且在某个时候遇到这个问题的底部会很棒。
你有没有找到解决方案?我现在正在处理类似的问题。 – 2013-03-05 23:46:34