2013-07-12 18 views
1

我有一個簡單has_and_belongs_to_many關係在Mongoid設置像這樣:mongoid before_destroy回調

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或一些其他的回調作者更新帖子計數?

回答

0

我不認爲Mongode關係中有任何內建功能可以幫助解決這個問題,但是你可以做的是在帖子上添加一個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

+0

我需要它的工作更新時,郵政,不刪除 - 是不是也有類似的方法,我可以用這個? – koosa

+0

我的歉意我讀錯了這個問題。 Mongoid也爲關聯更改提供了回調,我更新了答案。 –

相關問題