mongoid before_destroy对has_and_belongs_to_many关联的回调

时间:2013-07-12 14:09:08

标签: ruby-on-rails ruby mongodb mongoid

我在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模型并销毁作者/帖子关系时,如何对作者进行before_destroy或其他一些回调以更新帖子计数?

1 个答案:

答案 0 :(得分:0)

我不相信Mongoid关系中有任何内置功能可以帮助解决这个问题,但你可以做的是在帖子上添加一个before_destroy回调,告诉每个作者属于它的所有者。通过简单地触发该作者的保存来删​​除,以便调用您的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