Sebastian Wramba
Sebastian Wramba

Reputation: 10127

Modify has_many models of same class in after_save callback

So I have this class:

class Element < ActiveRecord::Base                                                                                     

  after_save :update_related_elements_pages                           

  belongs_to :page, counter_cache: true                               

  belongs_to :element, counter_cache: true                            
  has_many :elements

  def update_related_elements_pages
    self.elements.each do |rel_elem|       
      rel_elem.page_id = self.page_id
      rel_elem.save
    end
  end

end

Now when I update the Page association of an element, I would like all elements belonging to the current element to have the updated relationship as well. As you can see, I tried using a callback to achieve this.

The callback is called but unfortunately, self.elements is empty. Did I miss something? Is there a better way to do this? I could also do this in the controller if it's the more appropriate place for this.

Upvotes: 0

Views: 190

Answers (1)

Chris Chattin
Chris Chattin

Reputation: 482

Try creating a join model and using has_many :through to handle the self-referential relationship.

Here's an excellent Railscast explaining it better than I could here: http://railscasts.com/episodes/163-self-referential-association

Another resource: http://blog.flatironschool.com/post/66285912527/self-referential-associations-aka-self-joins

Upvotes: 1

Related Questions