简体   繁体   English

强参数:允许使用符号数组

[英]Strong Parameters: Permit an array of symbols

I need to whitelist a long list of params for a form in my Rails app. 我需要在Rails应用程序中将一长串参数列表列入白名单。 I've made an array of symbols, each symbol having the name of a param I need to whitelist. 我制作了一个符号数组,每个符号都有我需要白名单的参数名称。 Is there a way I can pass this array into the permit method and have those params permitted? 有没有办法将这个数组传递给allow方法并允许那些参数被允许? The form does not pass the params as a hash. 表单不会将参数作为哈希传递。

form.rb form.rb

class Form < ApplicationRecord

  jsonb_accessor :fields,
                 salutation: :string, # personal info
                 first_name: :string,
                 last_name: :string,
                 birthday: :string,
                 marital_status: :string,
                 number_of_dependants: :string,
                 first_time_owner: :string,
                 spouse_deal: :string,
                 phone_cell: :string, # contact info
                ...

      def self.fields
        [:salutation, :first_name, :last_name,
         :birthday,
         :marital_status,
         :number_of_dependants,
         :first_time_owner,
         :spouse_deal,
         :phone_cell,
         :phone_home,
        ...
        ]
      end

end

forms_controller.rb Forms_controller.rb

  def form_params
    params.require(:form).permit(:name, Form.fields)
  end

I'm using the jsonb_accessor gem to store these fields in a JSON column in the Form table. 我正在使用jsonb_accessor gem将这些字段存储在Form表的JSON列中。 So I'll have a lot of different forms, each with different params. 因此,我将有很多不同的形式,每种形式都有不同的参数。 So I need to find a way to dynamically permit parameters. 因此,我需要找到一种动态允许参数的方法。 I think the above might be an OK solution. 我认为以上可能是一个好的解决方案。 Though I'd appreciate advice on a better solution. 虽然我很乐意提供更好的解决方案的建议。

由于Form.fields返回一个符号数组,因此只需将其展开即可将它们转换为单独的参数:

params.require(:form).permit(:name, *Form.fields)

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

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