Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check modified value in a model's before_save callback?

How can I read the value that a controller has set in a before_save callback?

Example:

I have a model with a url field. Before saving, I want to check if the url was changed. If so, do some stuff with both the new and old url.

Is that possible?

like image 465
Jacob Avatar asked Dec 17 '11 18:12

Jacob


3 Answers

Try something like this:

before_save { |m| if m.url_changed? ... }

Also see the docs on ActiveModel::Dirty

like image 70
Marek Příhoda Avatar answered Oct 31 '22 15:10

Marek Příhoda


better way

before :todo, if: :first_name_or_last_name_changed?

and your todo method

def first_name_or_last_name_changed?
   first_name_changed? || last_name_changed?
end

like image 2
jamesdelacruz Avatar answered Oct 31 '22 16:10

jamesdelacruz


If it has changed it should be in the params hash. If it hasn't changed it shouldn't be in there. Therefore, you can put this custom handling into the controller, or in a method on the model that does this.

If you really want to access it inbefore_save check the documentation on ActiveRecord callbacks, and you will see how to access the before and after values.

like image 1
jefflunt Avatar answered Oct 31 '22 16:10

jefflunt