Question

I have a Parent model that maintains a set of Tags based on an aggregation of all the tags of its children:

model Parent
   before_save :agregate_tags

   has_many :children
   has_many :tags

   def agregate_tags
     self.tags = self.children.flat_map(&:tags).uniq
   end

end

The Child model:

class Child
   belongs_to :parent, autosave: true
   has_many :tags
end

When I save the Child the parent is not saved. Why might this be?

When I save child here are no errors and there is no database activity related to Parent. It seems that no attempt is made to save it.

If I create a before_save callback on Child and save parent there, it saves successfully without error.

Was it helpful?

Solution

How are you saving child? If you're not creating or modifying an association with parent, rails doesn't modify the parent record. Would you really want rails updating parent needlessly every time you modify a child?

You'll need to use before_save to do what you wish (as you've mentioned).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top