user4965201 user4965201 - 2 months ago 7
Ruby Question

Ruby on Rails detect changes in attributes in update

Hi I have a Rails app in which i wanted to know if an attribute is changed which occurs within the hash
let me explain i have params for @user

"foo"=> {"name"=> "name1", "age"=> "15", "height"=> "120"}


now when i change only attribute age i want to know if the age is changed

what i tried is
@user.foo_changed?
but it will give true whenever anything changes in the foo hash but i want it to be true only when the age is changed . How can i achieve this ?

Answer

try :

if @user.foo.age == params[:user][:foo][:age]
     # not changed
else
    # changed
end

OR

@user.foo.age_changed?  # this will work in case foo is associated(nested) model with user and foo table has "age" field