Search code examples
ruby-on-railsrubyruby-on-rails-4strong-parameters

strong parameters not accepting array


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"=>"a@loclahost.com", "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?


Solution

  • 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