问题
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 id=@user.id
but i don't know how i can do that in rails !!!
回答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")
来源:https://stackoverflow.com/questions/21605186/undefined-method-update-attributes-in-rails-4