I have adopted and I’m not sure exactly why something isn’t working.
I have a pricable polymorphic association which I use for only a single model called Item. It looks like this:
class Item < ActiveRecord::Base
#price
has_one :price, :as => :pricable
accepts_nested_attributes_for :price
attr_accessible :price_attributes, :price, ....
I’d like to add to an Event model and have added the following:
class Event < ActiveRecord::Base
#price
has_one :price, :as => :pricable
accepts_nested_attributes_for :price
attr_accessible :price, :price_attributes
However, I am not able to set it:
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
Hmmm…. it looks like the relationship is set up correctly and that Event has access to price via attr_accessible. Any idea what else could be going on?
thx
Relationship appears to be defined correctly, however if e.price returns nil then obviously e.price.price= won’t work and return undefined method error. You need to build/create an associated price object first:
or if you would like to use nested attributes: