Astm
Astm

Reputation: 1710

Undefined method update_attributes in Rails

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?

Upvotes: 15

Views: 22237

Answers (3)

Walter Schreppers
Walter Schreppers

Reputation: 518

@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).

Upvotes: 0

Kirti Thorat
Kirti Thorat

Reputation: 53018

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")

Upvotes: 26

Mohammad Bon
Mohammad Bon

Reputation: 251

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])

Upvotes: 25

Related Questions