【问题标题】:Call Back for belongs_to association rails回调belongs_to关联rails
【发布时间】:2015-03-13 19:17:25
【问题描述】:

就像after_add 回调has_and_belongs_to_many 关联一样,是否有任何回调或解决方法来获取belongs_to 关联的after_add 功能。 一种解决方法是在保存回调和脏对象功能之后/之前使用。

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),因为它进入了无限循环。

【问题讨论】:

    标签: ruby-on-rails-4 associations belongs-to


    【解决方案1】:

    似乎尚未添加为 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
    

    这又是一个真正的 hack,可能存在一些更好的解决方案。

    【讨论】:

    • 谢谢,这是解决方案之一。我发现的另一个方法是使用 update_column,这样可以避免回调。
    【解决方案2】:

    重写setter方法怎么样? Rails 指南的考试为this here

    摘录哪些州

    覆盖生成的方法

    关联方法在一个模块中生成,该模块包含在 模型类,它允许您轻松地用自己的覆盖 方法并使用 super 调用原始生成的方法。为了 示例:

       class Car < ActiveRecord::Base   belongs_to :owner   belongs_to
         :old_owner
    
         def owner=(new_owner)
             self.old_owner = self.owner
             super
         end
       end
    

    如果您的模型类是 Project,则模块名为 项目::生成的关联方法。生成的关联方法 模块被包含在模型类中 (匿名)生成的属性方法模块,意思是 关联将覆盖具有相同属性的方法 名字。

    我很欣赏这是一个老问题,但我偶然发现它正在寻找类似的解决方案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      相关资源
      最近更新 更多