16

In Rails, I want to update my user record. I'm trying to use this command:

@user=User.update_attributes(:name=> params[:name], :user=> params[:username], :pass=> params[:password])

But I always get the error:

undefined method `update_attributes' 

What's the right way to update my user?

3 Answers 3

30

Update for Rails v >= 6.1

Use update method asupdate_attributes method was removed as part of Rails 6.1 Release

@user.update(name: "ABC", pass: "12345678")

For Rails v < 6.1

update_attributes is an instance method not a class method, so first thing you need to call it on an instance of User class.

Get the user you want to update : e.g. Say you want to update a User with id 1

 @user = User.find_by(id: 1)
 now if you want to update the user's name and password, you can do

either

 @user.update(name: "ABC", pass: "12345678")

or

 @user.update_attributes(name: "ABC", pass: "12345678")

Use it accordingly in your case.

For more reference you can refer to Ruby on Rails Guides.

You can use update_all method for updating all records. It is a class method so you can call it as Following code will update name of all User records and set it to "ABC" User.update_all(name: "ABC")

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Kirti Thorat , it work now and i understand the concept to update records in rails
+1 for signalling the use of update_all on arrays. The fact that update_attributes is applicable only to a member and not a collection is rather opaque...
25

It seems that as of Rails 6.1, the "update_attributes" method is not working anymore! You must use the "update" method like this:

@user=User.update(:name=> params[:name], :user=> params[:username], :pass=> params[:password])

3 Comments

Thank you! It took me a while to find this answer, and after years of using update_attributes I thought I was going crazy.
Is this as simple as a finding all and changing them to update? Or are there any other differences? It seems to work fine where I just changed it in my update user method...
@PhilCowan Yes, Just find and replace. But don't forget to push your codes before making big changes ;)
1

@user.update(...) also works in rails 6 and it fully replaces @user.update_attributes(...) from rails 5 code. You don't need to convert it to a class instance aka User.update call where you can get later issues when updating nested models (while @user.update also works on nested models just like the deprecated method update_attributes did in rails 5).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.