save object associate to another object automatically
Hi i have these classes:
class Core < ActiveRecord::Base
belongs_to :resource, :polymorphic => true
belongs_to :image, :class_name => 'Multimedia', :foreign_key => 'image_id'
end
class Place < ActiveRecord::Base
has_one :core, :as => :resource
end
If 开发者_如何学Ci try do launch this:
a = Place.find(5)
a.name ="a"
a.core.image_id = 24
a.save
name is saved. image_id no i want save automatically all changes in records in relationship with place class at a.save command. is possible?
thanks
Use :autosave => true
See section titled One-to-many Example for ActiveRecord::AutosaveAssociation.
You'll want something like:
class Place
has_one :core, :as => :resource, :autosave => true
end
Disclaimer:
The :autosave => true
should be used on the "parent" Object. It works great with has_one
and has_many
, but I've run into great difficulty attempting to use it on a belongs_to
. relationship.
I think that you can use the build_association
method to do that. For example,
a = Place.find(5)
a.name = "a"
a.build_core(:image_id => 24)
a.save
But it might only work if the place object was created before hand.
精彩评论