kinet
kinet

Reputation: 1780

Update the parent model on child after_save, using Mongo

A User has many Posts and a Post belongs_to a User. Both have a location. I'd like to store the location for each Post and update the User location with the most recent Post location. Is after_save the way to go? I'm very inexperienced with Mongo DB.

Post Model

class Post
  include Mongoid::Document
  belongs_to :user

  after_save :update_user_location
  field :location, :type => String

  def update_user_location
     #update user's location
  end
end

User Model

class User
  include Mongoid::Document

  has_many :posts
  field :location, :type => String
end

(Please don't say to just get the most recent post location, I need to store it separately for a reason...thx)

Upvotes: 1

Views: 1172

Answers (2)

Alex
Alex

Reputation: 4507

This should work:

def update_user_location
    self._parent.location = self.location
    self._parent.save
end

However I think I have noticed a bug, if you parent model (User) has some before_save function, the self._parent.save is not effective... I have encountered the case twice already and could not find any explanation for it.

Alex

Upvotes: 0

Dhruva Sagar
Dhruva Sagar

Reputation: 7307

This should do it, have you tried anything ? Btw This is really a Mongoid specific question, not really related to MongoDB itself.

def update_user_location
    self.user.location = self.location
    self.user.save
end

Upvotes: 1

Related Questions