ChuckE
2012-Oct-18 12:56 UTC
ActiveRecord: updating an association of an already persisted instance in memory without making the update persist right away. Is this possible?
Hi,
I have ClassA, which has many objects of ClassB. Let''s say that the
dependency of that relationship is of the destroy kind:
class ClassA < ActiveRecord::Base
has_many :class_bs, :dependency => :destroy
end
class ClassB < ActiveRecord::Base
belongs_to :class_a
end
Now let''s say I already have a persisted instance of ClassA, and this
instance has also associated persisted objects:
a = ClassA.first
a.persisted #=> true
a.class_bs.length #=> >1
a.class_bs,all?{|b|b.persisted?} #=> true
So now, I would like to replace my associated class_bs with a new
collection of only one element, which is not persisted. I would like to
keep this only in memory, until I save the parent (or its child, for all I
care):
new_bs = [ClassB.new]
new_bs.all?{|b| b.new_record? } #=> true
a.class_bs = new_bs
a.class_bs.all?{|b| b.new_record?} #=> true
a.save
a.class_bs.all?{|b| b.new_record?} #=> false
Problem is, the way it works, step 4 will return "false" instead of
true.
That is, as soon as I assign something to an already persisted parent, the
new associations are stored right away (unless they are invalid). This is
something that I don''t like, because I may want to associate a to
another
object x, and I want to validate everything before I persist the changes,
but the way it works, as soon as I get to x, changes were already made. Is
there a way to do this in AR? and still keep the dependency => destroy?
Thanks in advance
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Core" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/rubyonrails-core/-/EWRssQGCFw4J.
To post to this group, send email to rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to
rubyonrails-core+unsubscribe@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/rubyonrails-core?hl=en.