我已经采用了,但我不确定为什么有些东西不起作用。
我有一个昂贵的多态关联,我只将它用于一个名为 Item 的模型。它看起来像这样:
class Item < ActiveRecord::Base
#price
has_one :price, :as => :pricable
accepts_nested_attributes_for :price
attr_accessible :price_attributes, :price, ....
我想添加到事件模型并添加了以下内容:
class Event < ActiveRecord::Base
#price
has_one :price, :as => :pricable
accepts_nested_attributes_for :price
attr_accessible :price, :price_attributes
但是,我无法设置它:
ruby-1.9.2-p290 :001 > e=Event.find(19) #ok
ruby-1.9.2-p290 :002 > e.price
Creating scope :page. Overwriting existing method Price.page.
Price Load (0.8ms) SELECT `prices`.* FROM `prices` WHERE `prices`.`pricable_id` = 19 AND `prices`.`pricable_type` = 'Event' LIMIT 1
=> nil
ruby-1.9.2-p290 :003 > e.price.price=23
NoMethodError: undefined method `price=' for nil:NilClass
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.0/lib/active_support/whiny_nil.rb:48:in `method_missing'
from (irb):3
嗯....看起来关系设置正确,并且 Event 可以通过 attr_accessible 访问价格。知道还会发生什么吗?
谢谢