如何允许散列

时间:2016-09-29 21:36:05

标签: ruby-on-rails arrays ruby hash

我在Ruby on Rails工作,我试图使用Ruby的许可功能允许散列中的所有值。这似乎很简单,但我无法让这个工作。我已经审核了许可证上的参考资料,并回答了这个SO问题how to permit an array with strong parameters

这是我的代码

PERMITTED_PARAMS = [
  :OriginCity,
  :OriginState,
  { :PickupDates => {}}
].freeze
params = {"OriginCity"=>"Denver", "OriginState"=>"CO", "PickupDates"=>{"0"=>"2016-09-30"}}
filtered_params = params.permit(PERMITTED_PARAMS)

并且,filtered_pa​​rams的结果值是

{"OriginCity"=>"Denver", "PickupDates"=>{}}

虽然filter_params的期望值是

{"OriginCity"=>"Denver", "PickupDates"=>{"0":"2016-09-30"}}

有关如何通过更改PERMITTED_PARAMS获取所需值的任何建议吗?

1 个答案:

答案 0 :(得分:0)

您希望允许散列中的所有值,而不是数组,这与您链接的示例不同。

试试这个:

PERMITTED_PARAMS = [
  :OriginCity,
  :OriginState
].freeze
params = {"OriginCity"=>"Denver", "OriginState"=>"CO", "PickupDates"=>{"0"=>"2016-09-30"}}
filtered_params = params.permit(PERMITTED_PARAMS).tap do |whitelisted|
  whitelisted[:PickupDates] = params[:PickupDates]
end

另请参阅:Strong parameters: allow hashes with unknown keys to be permitted