Search code examples
ruby-on-railsrails-activerecord

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?


Solution

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