简体   繁体   English

如何允许数组使用强参数?

[英]How to permit Array in strong parameters?

I'm actually posting an Array of ids to my Rails API but the array is received as a hash where the keys are the index of the array. 我实际上是将ID数组发布到我的Rails API,但是该数组以散列形式接收,其中键是数组的索引。

I already try permitting the parameters params.permit(permission_ids: []) and nothing... 我已经尝试过允许参数params.permit(permission_ids: []) ,什么也没有...

User migration 用户迁移

class CreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.string :username, null: false
      t.string :email, null: true
      t.integer :language_id, null: false
      t.integer :permission_ids, array: true, default: []
      t.string :password_digest, null: false
      t.timestamps
    end
    add_index :users, :username, unique: true
  end
end

User params method in the controller. 控制器中的用户参数方法。

  def user_params
    params.require(:user).permit(:username,
                                 :email,
                                 :language_id,
                                 :password,
                                 :password_confirmation,
                                 permission_ids: [])
  end

How parameters are received 如何接收参数

Parameters: {"user"=>{"username"=>"someusername", "email"=>"someemail@question.com", "language_id"=>"2", "permission_ids"=>{"0"=>"1", "1"=>"2", "2"=>"3", "3"=>"4", "4"=>"5", "5"=>"6", "6"=>"7", "7"=>"8", "8"=>"9", "9"=>"10", "10"=>"11", "11"=>"12"}}}

By the way, I'm posting from Vue using Axios. 顺便说一句,我正在使用Axios从Vue发布。

Can you also update the question with html form that is submitting this data. 您也可以使用提交此数据的html表单更新问题。 Issue could be in the form as well. 问题也可以是形式。

When you want the form to submit an entry as array, the form attribute should be 当您希望表单将条目提交为数组时,form属性应为

user['permission_ids'][]

By this, the html form will understand that the input to permission_ids in the html form, will be submitting an array. 这样,html表单将了解到html表单中对permission_ids的输入将提交一个数组。

For more info: https://stackoverflow.com/a/45233604/4940278 有关更多信息: https : //stackoverflow.com/a/45233604/4940278

The way I manage to get the array of ids: 我设法获取ID数组的方式:

def user_params
    params[:user][:permission_ids] = (params.dig(:user, :permission_ids) || {}).values
    params.require(:user).permit(:username,
                                 :email,
                                 :language_id,
                                 :password,
                                 :password_confirmation,
                                 permission_ids: [])
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM