ActiveRecord: updating an association of an already persisted instance in memory without making the update persist right away. Is this possible?


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
class ClassB < ActiveRecord::Base
belongs_to :class_a

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 = []
new_bs.all?{|b| b.new_record? } #=> true
a.class_bs = new_bs
a.class_bs.all?{|b| b.new_record?} #=> true
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