简体   繁体   English

after_update回调问题

[英]after_update callback issue

I have a model A which has association with another model Company. 我有一个与另一个模型公司有关联的模型A。 So, I call it as A.find(5).companies 因此,我将其称为A.find(5).companies

I want to do something in after_update callback of A. I add some companies in A.find(5).companies and want to know which companies got added in the callback. 我想在A的after_update回调中做一些事情。我在A.find(5).companies中添加了一些公司,并且想知道在回调中添加了哪些公司。 But in after_update callback, how can I get the list of companies in A.find(5).companies before the update? 但是在after_update回调中,如何在更新之前获取A.find(5).companies中的公司列表?

You can do this in the on_create callback of model Company . 您可以在Model Companyon_create回调中执行此操作。 Whenever a new company is added, you can see value of A from this and do your task. 每当添加新公司时,您都可以从中看到A的价值并完成任务。

You can create a logic using the created_at and updated_at timings . 您可以使用created_at和updated_at时序创建逻辑。

Once you will fire after_update callback for model A the updated_at filed of the table will be updated and you can get the list of companies where created_at time is later then the updated at of model A. 一旦您为模型A触发after_update回调,表的Updated_at文件将被更新,您可以获取created_at时间晚于模型A的公司列表。

.. in your controller.. when updating a model with accepts_nested_attributes_for ..在您的控制器中..当使用accepts_nested_attributes_for更新模型时

def update
  a.assign_attributes(params[:a])
  was_changed = a.companies.any?{|c| c.changed?} 
  a.save
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM