12

I have this in my view which is a multiselect checkbox

Model

class User < ActiveRecord::Base
  has_many :user_roles, :dependent => :destroy
  accepts_nested_attributes_for :user_roles, :allow_destroy => true
  has_many :roles, :through => :user_roles
end

view

<%= check_box_tag 'user[role_ids][]', role.id, user.blank? ? nil : user.roles.include?(role) ,id: dom_id(role)%>

the strong parameters for this is written as

  def user
    params.require(:user).permit(:first_name,{:role_ids => []})
  end

But on create it says

Processing by Admin::UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"+y8iWya5KIILqS0embEUEZuClycXq0O9Q4pA+MnbM0g=", "user"=>{"first_name"=>"", "last_name"=>"", "email"=>"[email protected]", "language"=>"en", "access_level_id"=>"1", "role_ids"=>["", "1", "", "5", "", "", ""], "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create user"}

Unpermitted parameters: role_ids
Unpermitted parameters: role_ids
Unpermitted parameters: role_ids
Unpermitted parameters: role_ids

Any clue why is it not accepting the array of role_ids which is coming from form?

3 Answers 3

21

See the Rails Strong Parameters documentation regarding nested attributes.

The correct format is:

params.permit(:name, {:roles => []}, ...)

AnkitG's solution worked for me in Rails 4 using the Role Model gem for my user model. My user controller's implementation of _params ended up looking like:

def user_params
  # Bug with permit for nested arrays... @see https://stackoverflow.com/a/17880288/2631472
  params.require(:user).permit(:first_name, :last_name, :middle_name).tap do |whitelisted|
    whitelisted[:roles] = params[:user][:roles]
  end
end

Sign up to request clarification or add additional context in comments.

Comments

8

This should work

params.require(:user).permit(:first_name, :role_ids => [])

4 Comments

paste your create method pls
created a GIST here . Please have a look
can you post error message when you do it this way? I tried it in the console and it works correctly (using the parameters in your question)
How do I specify role_ids as a separate key?
7

Answering myself, I got it working not directly, but the below method from the Strong Parameters issues discussion helped me in converting a normal parameter to a whitelisted one.

def user_params
  params.require(:user).permit(:first_name).tap do |whitelisted|
    whitelisted[:role_ids] = params[:user][:role_ids]
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.