how to autobuild an associated polymorphic activerecord object in rails 3 -



how to autobuild an associated polymorphic activerecord object in rails 3 -

class itemsource < activerecord::base belongs_to :product, :polymorphic => true end class randomproduct < activerecord::base has_one :item_source, :as => :product, :autosave => true, :dependent => :destroy end

what i'd is call:

a = randomproduct.find(1) a.item_source

and if item_source doesn't exist (= nil), build automatically (build_item_source).

previously, did alias_chain_method, that's not supported in rails 3. oh, , tried no avail:

class randomproduct < activerecord::base has_one :item_source, :as => :product, :autosave => true, :dependent => :destroy module autobuilditemsource def item_source super || build_item_source end end include autobuilditemsource end

in rails 3, alias_method_chain (and alias_method, , alias) work fine:

class user < activerecord::base has_one :profile, :inverse_of => :user # works: # # def profile_with_build # profile_without_build || build_profile # end # alias_method_chain :profile, :build # # this: alias profile_without_build profile def profile profile_without_build || build_profile end end

but there's accept_nested_attributes_for alternative, calls build when profile_attributes set. combine delegate (optional) , won't have worry if record exists or not:

class user < activerecord::base has_one :profile, :inverse_of => :user delegate :website, :to => :profile, :allow_nil => true accepts_nested_attributes_for :profile end user.new.profile # => nil user.new.website # => nil u = user.new :profile_attributes => { :website => "http://example.com" } u.profile # => #<profile id: nil, user_id: nil, website: "http://example.com"...>

if association created, delegation isn't necessary (but may helpful, anyhow).

(note: set :inverse_of create profile.validates_presence_of :user work , save queries.)

activerecord ruby-on-rails-3

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -