强参数不接受数组 [英] strong parameters not accepting array

查看:45
本文介绍了强参数不接受数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是一个多选复选框

I have this in my view which is a multiselect checkbox

模型

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 数组的任何线索?

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

推荐答案

回答我自己,我不是直接工作,而是以下方法来自 强参数问题讨论帮助我将普通参数转换为白名单参数.

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

这篇关于强参数不接受数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆