RicciFlowing
RicciFlowing

Reputation: 11

Rails: Update to ancestry parent not persisted

I tried to change the parent of all siblings of an ancestry model (code from the activity model):

def change_parents_of_siblings
  to_change = self.siblings.where.not(id: self.id)
  to_change.each do |sib|
    sib.update!(parent: self)
  end
end

If I print all the ids inside the function (like sib.id, ...) to the console it seems to work. But after the function call none of these changes are persisted. For example:

@activity1 = Activity.create(name:"test1")
@activity2 = Activity.create(name:"test2", parent_id: @activity1.id )
@activity15 = Activity.create(name:"test1.5", parent_id: @activity1.id)
@activity15.change_parents_of_siblings

expect(@activity2.parent_id).to eq(@activity15.id)

fails.

Upvotes: 0

Views: 690

Answers (1)

RicciFlowing
RicciFlowing

Reputation: 11

After taking a bath I found the problem myself.

The change_parents_of_siblings method changed the ancestry in the database. BUt this is not recognized by Rails as a change on the model.

So I had to call @activity2.reload before using it again.

Sorry for taking your time.

Upvotes: 1

Related Questions