强参数不接受数组

时间:2013-07-26 10:45:51

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

我在我的视图中有这个多选复选框

模型

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

查看

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

此强参数写为

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

但是在创造它说

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

任何线索为什么它不接受来自表单的role_id数组?

3 个答案:

答案 0 :(得分:21)

请参阅Rails Strong Parameters documentation regarding nested attributes

正确的格式是:

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

AnkitG's solution使用Role Model gem为我的用户模型在Rails 4中为我工作。我的用户控制器的_params实现最终看起来像:

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

<击>

答案 1 :(得分:8)

这应该有效

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

答案 2 :(得分:7)

回答自己,我没有直接开始工作,但Strong Parameters issues discussion中的以下方法帮助我将正常参数转换为白名单参数。

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