Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my model Shop I'm saving image url in logo_ori and use that to make thumbnails using 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_ori is saved?

I've tried this :

before_update :run_blitline_job, :if => :logo_ori?

but it still runs before_update if I already have logo_ori saved earlier.

like image 293
hsym Avatar asked Dec 29 '12 05:12

hsym


2 Answers

before_update :run_blitline_job, :if => :logo_ori_changed?

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

before_update :run_blitline_job, :if => proc { !logo_ori_was && logo_ori_changed? }
like image 174
John H Avatar answered Nov 09 '22 09:11

John H


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/ActiveModel/Dirty.html

like image 3
Brad Werth Avatar answered Nov 09 '22 10:11

Brad Werth