2011-10-13 39 views
1

在我的Rails應用程序,有一個樹狀模型是這樣的:定製的setter爲Mongoid外鍵屬性使用Rails

class File 
    belongs_to :parent, :foreign_key => "parent_id", :class_name => "File" 
end 

我想將功能添加到父二傳手的行爲。所以像這樣的東西(除非它不起作用)?

def parent=(new_parent) 
    super(new_parent) 
    # Additional stuff I want to do here 
end 

我需要的默認行爲依然存在,因爲我覺得它管理的關係,但我需要知道什麼時候父被改變,所以我可以做一些額外的工作。

回答

0

的解決方法我現在有是這樣的:

class File 
    belongs_to :parent, :foreign_key => "parent_id", :class_name => "File" 
    before_save :check_parent 

    def check_parent 
    if self.parent_id_changed? 
     # Additional stuff I want to do here 
    end end end 

唯一的缺點是,你必須拯救這個踢理想我希望它儘快PARENT_ID改變一命嗚呼。否則,這工作得很好,雖然我會打開更好的解決方案。