【问题标题】:undefined method `update_attributes' for ## 未定义的方法“update_attributes”
【发布时间】:2021-06-09 01:07:40
【问题描述】:

我收到此错误

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

我想用这样的形式编辑用户信息;

这是我的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

这是我的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>

这是我的_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' %>

我尝试查看@user,但是当涉及update_attributes 时,它给出了这个错误。

【问题讨论】:

    标签: ruby-on-rails ruby forms model-view-controller


    【解决方案1】:

    此方法已被弃用或在最新的稳定版本上移动。

    update_attributes 已经是 已被弃用。

    您可以改用update

    @user.update(user_params)
    

    【讨论】:

    • @AmirulAsyraf 您应该将答案标记为已接受。
    【解决方案2】:

    update_attributes(params) 方法已弃用,不应再使用。您必须改用update(params)。 所以你的代码看起来像这样:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多