Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method update_attributes in Rails 4

i'm now using Rails 4 now 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])
OR
@user=User.update_attributes(name: params[:name], user: params[:username], pass: params[:password])

but always got the error

undefined method `update_attributes' 

so how i can update my user also i want to ask is it will update all the users in my DB ??

i think i must add some condition such as where [email protected] but i don't know how i can do that in rails !!!

like image 898
Astm Avatar asked Feb 06 '14 14:02

Astm


2 Answers

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

like image 176
Kirti Thorat Avatar answered Oct 23 '22 10:10

Kirti Thorat


It seems that 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])
like image 32
Mohammad Bon Avatar answered Oct 23 '22 10:10

Mohammad Bon