【问题标题】:Update the parent model on child after_save, using Mongo使用 Mongo 在子 after_save 上更新父模型
【发布时间】:2011-09-20 23:08:16
【问题描述】:

一个用户有很多帖子,一个帖子属于一个用户。两者都有位置。我想存储每个帖子的位置,并使用最新的帖子位置更新用户位置。 after_save 是要走的路吗?我对 Mongo DB 非常缺乏经验。

后模型

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

用户模型

class User
  include Mongoid::Document

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

(请不要说只获取最近的发布位置,我需要单独存储它是有原因的...thx)

【问题讨论】:

    标签: ruby-on-rails ruby mongodb model mongoid


    【解决方案1】:

    这应该可以,你有没有尝试过?顺便说一句,这确实是一个特定于 Mongoid 的问题,与 MongoDB 本身并没有真正的关系。

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

    【讨论】:

      【解决方案2】:

      这应该可行:

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

      但是我想我注意到了一个错误,如果您的父模型(用户)有一些 before_save 功能,self._parent.save 无效...我已经遇到过两次这种情况,找不到任何解释它。

      亚历克斯

      【讨论】:

      • Alex,这正是我的问题。我尝试将 before_save 更改为 after_validation,它对我有用。奇怪,我以为只有我……我还是 mongo 的新手
      • 是的,仍然有一些古怪的行为,但我相信这是 mongoid 而不是 mongodb
      猜你喜欢
      • 1970-01-01
      • 2020-12-04
      • 2021-04-25
      • 2013-08-26
      • 2017-06-06
      • 2010-11-09
      • 2017-05-30
      • 2019-04-15
      • 1970-01-01
      相关资源
      最近更新 更多