Question

I'm trying to update single attribute of a user model from a admin controller (not users controller).

While doing this I tried update_attribute() but it was changing the users password also.

I think the password is changing because I have before_save method on user model which hashes the password.

update_attributes() is not working because it is checking the validations for password which is presence=>true

Is there any way to achieve this?

Was it helpful?

Solution

Try update_column(name, value), it might work.

OTHER TIPS

You can set a condition on your validations by using the :if option. In my code, it looks something like this:

validates :password,
          :length => { :minimum => 8 },
          :confirmation => true,
          :presence => true,
          :if => :password_required?


def password_required?
  crypted_password.blank? || password.present?
end

So basically, it's only if the crypted_password in the database is not set (meaning a new record is being created) or if a new password is being provided that the validations are run.

You can update single attribute of user like this

@user is that user whose attribute you want to update

e.g user_name

       @user.update_attributes(:user_name => "federe")

Try it and it will only update one attribute..

ActiveRecord has an 'update-column' method that skips both validations and callbacks:

http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_column

However, I'd suggest that could be dangerous - you have that :before_save filter for a reason. If you place an :except method on the filter to circumvent in specific cases, it not only becomes reusable but you keep behaviour consistent and avoid having a method buried in a controller that's bypassing your Model's validation/callback stack.

I'm personally not overly keen on seeing methods like update_column anywhere except as protected methods inside Models.

Try :

To bypass callback and validations use :

User.update_all({:field_name => value},{:id => 1})

Just wanted to let you know :

  • In Rails, update_attribute method bypasses model validations, while update_attributes and update_attributes! will fail (return false or raise an exception, respectively) if a record you are trying to save is not valid.

  • The difference between two is update_attribute use save(false) where as update_attributes uses save or you can say save(true) .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top