1

我在 Mongoid 中设置了一个简单的 has_and_belongs_to_many 关系,如下所示:

class Post

  ...

  has_and_belongs_to_many :authors

  scope :live, lambda{ published.where(:published_at.lt => Time.now) }

end


class Author

  has_and_belongs_to_many :posts

  before_save :count_posts

  def count_posts
    self.post_count = posts.live.length
  end

end

当我更新 Post 模型并销毁 Author / Post 关系时,如何对作者执行 before_destroy 或其他回调来更新帖子计数?

4

1 回答 1

0

我不相信 Mongoid 关系中内置的任何功能可以帮助解决这个问题,但你可以做的是在帖子上添加一个 before_destroy 回调,告诉每个作者它属于它,只需触发一个保存它就被删除了author 以便调用您的 count_posts 挂钩。

class Post
    has_and_belongs_to_many :authors

    after_remove :update_author_counts

    scope :live, lambda{ published.where(:published_at.lt => Time.now) }

    ....

    protected

    def update_author_counts
        # Assuming you keep the count_posts callback in
        # your author model, all you have to do is trigger a save
        authors.each { |a| a.save }
    end  

end

参考: http: //mongoid.org/en/mongoid/docs/callbacks.html

于 2013-07-12T14:21:50.160 回答