回拨为belongs_to的关联轨道

问题描述:

after_add回调has_and_belongs_to_many协会是没有任何回调或解决以获取belongs_to的关联after_add功能。 解决方法之一是在保存回调函数和脏对象功能之前/之后使用。回拨为belongs_to的关联轨道

belongs_to :video 
after_save :after_save_task 

def after_save_task 
do_stuff if video_id_changed? 
end 

def do_stuff 
### do stuff 
end 

但我可以在do_stuff不save(true)自进入无限循环。

看起来像是还没有被添加添加回调has_on和belongs_to的功能。看到这个线程您的具体问题https://github.com/rails/rails/issues/586

一个肮脏的解决办法是增加一些肮脏的属性,如果更新已经作出建议。

这样

belongs_to :video 
after_save :after_save_task 
attr_accessor :stuff_done 

def after_save_task 
do_stuff if video_id_changed? && !stuff_done 
end 

def do_stuff 
stuff_done = true 
### do stuff 
## Saving record here would be fine. 
end 

再次,这是一个真正的黑客,可能存在一些这方面的更好的解决方案。

+0

谢谢你,解决它的一个。我发现的另一个是使用update_column,这将避免回调。 – 2015-03-16 15:52:41

重写setter方法如何? Rails的引导件具有this here

其中指出

重写生成的方法

被纳入 模型类的模块中生成关联方法的摘录的exam0le,这使您可以轻松地使用自己的方法进行覆盖,并使用super调用原始生成的方法。对于 例如:

class Car < ActiveRecord::Base belongs_to :owner belongs_to 
    :old_owner 

    def owner=(new_owner) 
     self.old_owner = self.owner 
     super 
    end 
    end 

如果你的模型类项目,该模块被命名为 项目:: GeneratedAssociationMethods。 GeneratedAssociationMethods 模块在 (匿名)生成的属性方法模块之后立即包含在模型类中,这意味着 关联将覆盖具有相同 名称的属性的方法。

我明白这是一个老问题,但我无意中发现了它寻找一个类似的解决方案