强参数:允许符号数组

dom*_*91c 1 ruby ruby-on-rails strong-parameters

我需要在我的Rails应用程序中为一个表单列入一长串params列入白名单.我制作了一系列符号,每个符号都有一个我需要列入白名单的参数名称.有没有办法可以将这个数组传递给permit方法并允许这些参数?表单不会将params作为哈希传递.

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
Run Code Online (Sandbox Code Playgroud)

forms_controller.rb

  def form_params
    params.require(:form).permit(:name, Form.fields)
  end
Run Code Online (Sandbox Code Playgroud)

我正在使用jsonb_accessor gem将这些字段存储在Form表的JSON列中.所以我会有很多不同的形式,每个都有不同的参数.所以我需要找到一种动态允许参数的方法.我认为以上可能是一个好的解决方案.虽然我很欣赏有关更好解决方案的建议.

Mic*_*ohl 5

因为Form.fields返回一个符号数组,你可以将其展开以将它们转换为单独的参数:

params.require(:form).permit(:name, *Form.fields)
Run Code Online (Sandbox Code Playgroud)