我正在尝试允许具有任意数量值的数组,但Rails每次都会抛出Unpermitted parameter: service_rates
。我尝试了很多东西(Rails 4 Unpermitted Parameters for Array,Unpermitted parameters for Dynamic Forms in Rails 4,......)但没有任何作用。
字段的名称为service_rates
,其列类型为jsonb
。
我想从任意数量的输入字段创建一个JSON对象:
<%= f.hidden_field :service_ids, value: @services.map(&:id) %>
<% @services.each do |service| %>
<tr>
<td>
<% value = @project.service_rates ? @project.service_rates["#{service.id}"]['value'] : '' %>
<%= text_field_tag "project[service_rates][#{service.id}]", value, class: 'uk-width-1-1', placeholder: 'Stundensatz' %>
</td>
</tr>
<% end %>
所以我的POST
数据如下所示:
project[service_rates][1] = 100
project[service_rates][2] = 95
project[service_rates][3] = 75
目前service_rates
允许通过tap
列入白名单:
def project_params
params.require(:project).permit(:field1, :field2, […], :service_ids).tap do |whitelisted|
whitelisted[:service_rates] = params[:project][:service_rates]
end
end
至少,我在私有模型函数中构建一个JSON对象(抛出此错误):
class Project < ActiveRecord::Base
before_save :assign_accounting_content
attr_accessor :service_ids
private
def assign_accounting_content
if self.rate_type == 'per_service'
service_rates = {}
self.service_ids.split(' ').each do |id|
service_rates["#{id}"] = {
'value': self.service_rates["#{id}"]
}
end
self.service_rates = service_rates
end
end
end
我也试图允许这样的领域......
params.require(:project).permit(:field1, :field2, […], :service_rates => [])
......那......
params.require(:project).permit(:field1, :field2, […], { :service_rates => [] })
......但这也不起作用。
当我试试这个......
params.require(:project).permit(:field1, :field2, […], { :service_rates => [:id] })
...我明白了:Unpermitted parameters: 1, 3, 2
答案 0 :(得分:1)
service_rates
对你来说并不是很清楚。它是协会的名称吗?或者只是一个字符串数组?
允许字符串数组::array => [],
允许嵌套参数用于关联:association_attributes: [:id, :_destroy, ...]
params.require(:object).permit(
:something,
:something_else,
....
# For an array (of strings) : like this (AFTER every other "normal" fields)
:service_rates => [],
# For nested params : After standard fields + array fields
service_rates_attributes: [
:id,
...
]
)
正如我在评论中所解释的那样,订单很重要。您的白名单数组必须出现在每个经典字段之后
修改强>
您的表单应使用f.fields_for
来嵌套属性
<%= form_for @project do |f| %>
<%= f.fields_for :service_rates do |sr| %>
<tr>
<td>
<%= sr.text_field(:value, class: 'uk-width-1-1', placeholder: 'Stundensatz' %>
</td>
</tr>
<% end %>
<% end %>