Rails 4错误:ActionController :: ParameterMissing在UsersController#update中,param not found:user

时间:2014-06-18 19:31:50

标签: ruby-on-rails ruby strong-parameters

我有一个标准CRUD方法的用户控制器。其中一种方法是更新。

def update
    if @user.update(user_params)
        redirect_to @user, notice: "Account Successfully updated"
    else
        render :edit
    end
end

然后我有轨道4强params方法:

private
def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation, :role_ids => [])
end

我的观点是这样的:

<% if is_admin?(current_user) %>
    <%= hidden_field_tag "user[role_ids][]", nil %>
    <% Role.all.each do |role|%>
    <%= check_box_tag "user[role_ids][]", role.id, @user.role_ids.include?(role.id) %>
    <%= role.name %><br>
    <% end %>
<% end%>
</br></br>

<footer>
<nav>
<%= link_to "Update User", user_path(@user), :method => :put%>
</nav>
</footer>

单击视图中的更新用户链接时。我收到这个错误:

 ActionController::ParameterMissing in UsersController#update
 param not found: user

错误的突出显示行是:

  private
  def user_params 
 params.require(:user).permit(:name, :email, :password, 
 :password_confirmation, :role_ids => [])
        end

我似乎无法解释为什么我得到这个错误,因为强大的params条件得到满足。

有什么想法吗?


请求参数:

Started PUT "/users/4" for 127.0.0.1 at 2014-06-18 16:33:58 -0400
Processing by UsersController#update as HTML
  Parameters: {"authenticity_token"=>"1JONmLnMcf2A/2y9boXmcPG5UiwahyR0loLfw+lshco=", "id"=>"4"}
  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 4 LIMIT 1
  User Load (0.1ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 4 LIMIT 1
  CACHE (0.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 4 LIMIT 1  [["id", 4]]
Completed 400 Bad Request in 2ms

ActionController::ParameterMissing (param not found: user):
  app/controllers/users_controller.rb:49:in `user_params'
  app/controllers/users_controller.rb:32:in `update'

1 个答案:

答案 0 :(得分:8)

这是因为您没有将params嵌套在“user”键中。

.require(:user)正在寻找这样的哈希:

{"user"=>{params}}

表单不正确,您必须在发送之前添加用户密钥。

<%= form_for @user, url: {action: "update"} do |f| %>
  #form items.

  <%= f.submit "Create" %>
<% end %>

编辑:

您可以将此操作的参数重新定义为:

private
def user_params
    params.permit(:name, :email, :password, :password_confirmation, :role_ids => [])
end