开发者

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, 开发者_StackOverflow中文版I need to store it separately for a reason...thx)


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜