Re-associating a child with another parent - Rails (2.3.11) delete has_many related object without sql operation

Given the following definitions

Foo
    has_many :bars, :dependent => :nullify, :autosave => false

Bar
    validates_presense_of :foo
    foo_id is not null # database constraint

I would like to associate a Bar object with another Foo object. I need all this to be done correctly in memory, so I can display everything in case it fails after completing the health check.

The problem is that I am doing something like

bar.foo.bars.delete(bar)
bar.foo = other_foo
other_foo.bars << bar

I get a failure that when bar.foo.bars.delete(bar)updating sql, it cancels the bar foo_id property. Hence the exception and failure of sql constraints. Instead, I need it to just work in memory and, if necessary, validate.

Edit:

, , db, , , , db Bar. , , , . , , ( ) , , .

, - :

:

foo1.bars => [bar1, bar2]
foo2.bars => [bar3]

foo1.bars => [bar1]
foo2.bars => [bar3, bar2]

, - ( ), , , , .

+3
2

(bar1) (foo1) ,

foo1.bars.delete_if{|b| b.id == bar1.id}

bar1 foo1 bars, bar1 , delete_if Enumerable, HasManyAssociation.

+1

before_destroy. Rails

0

All Articles