Bruce Lin
Bruce Lin

Reputation: 2740

Update updated_at on related has_and_belongs_to_many models in Mongoid

I have two models with has_and_belongs_to_many relationship.

class Person
  include Mongoid::Document
  include Mongoid::Timestamps
  has_and_belongs_to_many :stories;
end

class Story
  include Mongoid::Document
  include Mongoid::Timestamps
  has_and_belongs_to_many :people;
end

I'm trying to push an story to a person,

Person.stories << Story.first

and I'm expecting this will update the updated_at field for the person. However it is not updated. Is there a way to update the field? Shall I use touch?

Upvotes: 3

Views: 1347

Answers (2)

tudorpavel
tudorpavel

Reputation: 149

As ericpeters0n mentioned in his comment, the accepted answer only shows how to touch Child objects when Parents are updated.

If you want to touch Parent objects when Children are added/removed from the association, you can simply do:

class Person
  after_save :touch
end

class Story
  after_save :touch
end

Upvotes: 2

Buck Doyle
Buck Doyle

Reputation: 6397

This is discussed in this GitHub issue. The base object is not updated when a new related object is added. If you were using belongs_to you could add touch: true, but you’re not.

In the discussion of the issue, they recommend adding an after_save to the related object. In this case, you’d have to add it to both sides of the relation:

class Person
  after_save do
    stories.each(&:touch)
  end
end

class Story
  after_save do
    people.each(&:touch)
  end
end

Less than elegant, but should work?

Upvotes: 2

Related Questions