banditKing banditKing - 7 months ago 14
Ruby Question

Rails 4 error: ActionController::ParameterMissing in UsersController#update, param not found: user

I have a users controller with standard CRUD methods. One of the methods is Update.

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


Then I have the rails 4 strong params method:

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


My view is like so:

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


When I click the update User link in the view. I get this error:

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


The highlighted line for the error is:

private
def user_params



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



I cannot seem to explain why Im getting this error since the strong params condition is satisfied.

Any ideas?




Request 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'

Answer

This is because you are not nesting the params inside "user" key.

The .require(:user) is looking for a hash like this:

{"user"=>{params}}

The form is not correct, you have to add the user key before sending it.

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

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

EDIT:

You can redefine the params for this action to:

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