stefankroes/ancestry

Save children on model update

chrisvel opened this issue · 4 comments

I have a model called Post which can be linked to other posts but can also referenced from others too.

I also have a select element in my form with a multi-choice dropdown where the user marks some children as selected.

The form POSTs an array of ids with all selected children ids. What is the most proper/optimum way to update all children with the current(parent) Post's ids ?

I have tried with an after_save callback in the model but it creates a loop, so I moved it to the controller's update action.

if @post.update(post_params)
        current_user.posts.where(id: post_params[:link_ids]).each{|s| s.update(parent: @post)}

        format.html { redirect_to note_path......

This is terrible, but I can't get update_all to work, because parent is a virtual attribute

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column "parent" of relation "posts" does not exist

Any ideas ?

That is one issue with ancestry, parent is not a real relationship so it is not easy to work with.
I can't fix this any time soon but is in the long term radar.

So @post is the same parent for all records. Therefore ancestry is the same for all as well.

current_user.posts.where(id: post_params[:link_ids]).update_all(:ancestry => @post.ancestry)

Having said that, the posts's children should already be children of the post.

I do wonder what would happen with current_user.post_ids << post_pramams[:link_ids]
Not so sure about your logic here, something seems off, but that code will answer the question you are asking.

Did you get a chance to test that out?
Is this still a problem for you?

Were you able to resolve this?

I just figured it out it should be child_ancestry instead

current_user.posts.where(id: post_params[:link_ids]).each{|s| s.update(parent: @post)}

# these are the same:
node.update(parent: @parent)
node.update(ancestry: @parent.child_ancestry)

current_user.posts.where(id: post_params[:link_ids])
            .update_all(ancestry: @post.child_ancestry)

closing.