Asyraf
Asyraf

Reputation: 657

undefined method `update_attributes' for #

I get this error

NoMethodError in UsersController#update
undefined method `update_attributes' for #<User id: 1, 
first_name: "Bob", last_name: "Cool", 
created_at: "2021-03-10 06:06:13.238325000 +0000", 
updated_at: "2021-03-10 06:06:13.238325000 +0000">

I want to edit the user information with the form like this ;

enter image description here

This is my users_controller.rb ;

before_action :set_user, only: [:show, :edit, :update]

def update
    if @user.update_attributes(user_params)
      redirect_to root_path
    else
      redirect_to edit_user_path(@user), 
      error: @user.errors.full_messages.join(', ')
    end
  end

private
  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:first_name, :last_name)
  end

This is my edit.html.rb

<p>
  <%= form_with model: @user, url: user_path(id: @user.id), method: :put, local: true do |form| %>
    <%= render 'form', form: form %>
  <% end %>
</p>

This is my _form.html.erb

<%= form.label 'First Name: '%>
<%= form.text_field 'first_name' %>
<br/>
<%= form.label 'Last Name: '%>
<%= form.text_field 'last_name' %>
<br/>
<%= form.submit 'Submit' %>

I try to look at @user, but when it came to update_attributes, it gives this error.

Upvotes: 2

Views: 1999

Answers (2)

Daniel
Daniel

Reputation: 359

The method update_attributes(params) is deprecated and shouldn't be used anymore. you have to use update(params) instead. So your code would look like this:

def update
  if @user.update(user_params)
    redirect_to root_path
  else
    redirect_to edit_user_path(@user), 
    error: @user.errors.full_messages.join(', ')
  end
end

Upvotes: 1

eux
eux

Reputation: 3282

This method is deprecated or moved on the latest stable version.

update_attributes is already been depreated.

You could use update instead:

@user.update(user_params)

Upvotes: 10

Related Questions