Ruby-on-rails Rails:如何只为一个更改的属性运行 before_update?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14079013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:14:20  来源:igfitidea点击:

Rails: How to run before_update only for one changed attribute?

ruby-on-railsruby-on-rails-3activerecordbeforeupdate

提问by serial engine

In my model ShopI'm saving image url in logo_oriand use that to make thumbnails using before_update.

在我的模型中,Shop我将图像 url 保存在其中logo_ori并使用它来制作缩略图before_update

# shop.rb
before_update :run_blitline_job

private

def run_blitline_job
  # uses logo_ori to make thumbnails
end

However I found out that when I'm saving other attributes (eg: editing shop's profile in a form) it also runs before_update. How do I confine its execution when only logo_oriis saved?

但是我发现当我保存其他属性(例如:在表单中编辑商店的个人资料)时,它也会运行before_update. 仅logo_ori在保存时如何限制其执行?

I've tried this :

我试过这个:

before_update :run_blitline_job, :if => :logo_ori?

but it still runs before_updateif I already have logo_orisaved earlier.

before_update如果我之前已经logo_ori保存过,它仍然会运行。

回答by John H

before_update :run_blitline_job, :if => :logo_ori_changed?

This will run the callback every time the logo_oriattribute changes. You can also use strings to implement multiple conditionals:

这将在每次logo_ori属性更改时运行回调。您还可以使用字符串来实现多个条件:

before_update :run_blitline_job, :if => proc { !logo_ori_was && logo_ori_changed? }

回答by Brad Werth

You are close, you want something like this:

你很接近,你想要这样的东西:

before_update { |shop| shop.run_blitline_job if shop.logo_ori_changed? }

sources:

来源:

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

回答by Muhamamd Awais

its simple you can use ActiveModel::Dirty(checkout the documentation), it is available in all models in rails 3

它很简单,您可以使用ActiveModel::Dirty(查看文档),它适用于 rails 3 中的所有模型

before_update { |shop| shop.run_blitline_job if shop.logo_ori_changed? }