Search code examples
ruby-on-railsrubyruby-on-rails-3deviseactioncontroller

Object.attribute_changed? not working in Rails controller


I'm overwriting Devise user's registration controller to check if user has changed city and if so, load again the Geokit object in session.

session[:geo_location] = User.geocode(resource.city) if resource.city_changed?

Problem is that is not doing it. Nothing is return with the code below. If I remove the if resource.city_changed? it does it for all cases no matter if the resource has been changed or not.

 User::RegistrationsController < Devise::RegistrationsController

  def update 
   self.resource = resource_class.to_adapter.get!(send(:"current_#    {resource_name}").to_key)    
    if resource.update_with_password(params[resource_name])

      session[:geo_location] = User.geocode(resource.city) if resource.city_changed?

      set_flash_message :notice, :updated if is_navigational_format?
      sign_in resource_name, resource, :bypass => true
      respond_with resource, :location => after_update_path_for(resource)
    else
      clean_up_passwords(resource)
      respond_with_navigational(resource){ render_with_scope :edit }
    end

  end

end

Solution

  • Does update_with_password call save? If so, it clears the "dirty" state of the model and all its attributes. You would need to call resource.city_changed? after setting the attribute but before calling save.