brendon / acts_as_list

An ActiveRecord plugin for managing lists.
http://brendon.github.io/acts_as_list/
MIT License
2.04k stars 355 forks source link

Parent's `children` is not updated when being assigned directly to a child #362

Closed jmuheim closed 5 years ago

jmuheim commented 5 years ago

I have the following list structure:

root_element = create :element
sub_element = create :element, parent: root_element

I would expect that root_element now knows that it has a child sub_element, but it doesn't:

root_element.children
=> []

Only when I reload manually:

root_element.reload.children
=> [
    [0]  #<Element:0x007fd479ef9de0>
]

If I assign sub_element to the root_element...

root_element = create :element
sub_element = build :element, parent: root_element

root_element.children << sub_element

...this problem doesn't happen:

root_element.children # No reload necessary!
=> [
    [0]  #<Element:0x007fd479ef9de0>
]

Is this expected behaviour? Is there a way to make the code at the top work without the need of triggering reload manually?

brendon commented 5 years ago

Hi @jmuheim, this doesn't have anything to do with acts_as_list :)

You may want to look at the inverse_of option on your relationship declarations:

https://makandracards.com/makandra/12331-rails-when-to-use-inverse_of-in-has_many-has_one-or-belongs_to-associations

Especially true since this is a self-referential relationship and Rails probably won't know how to untangle that and guess the inverse.

Hope that helps :) Feel free to report back here if you solve it anyway.