【发布时间】:2017-03-09 03:30:30
【问题描述】:
我需要为我的 Rails 应用程序中的表单添加一长串参数列表。我制作了一组符号,每个符号都有我需要列入白名单的参数名称。有没有办法可以将此数组传递给 permit 方法并允许这些参数?表单不会将参数作为哈希传递。
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
def form_params
params.require(:form).permit(:name, Form.fields)
end
我正在使用 jsonb_accessor gem 将这些字段存储在 Form 表的 JSON 列中。所以我会有很多不同的形式,每个都有不同的参数。所以我需要找到一种动态允许参数的方法。我认为以上可能是一个好的解决方案。虽然我很感激有关更好解决方案的建议。
【问题讨论】:
-
params.require(:form).permit(:name, fields: [])?
标签: ruby-on-rails ruby strong-parameters