【问题标题】:Rails params attributes - using the params fields in the controllerRails 参数属性 - 使用控制器中的参数字段
【发布时间】:2017-03-10 10:36:58
【问题描述】:

我的 developers_controller 中有以下 strong 参数,名为 location_params

  def location_params
    params.require(:location).permit(:country, {:ads_attributes => [:remote, :days]})
  end

当我在代码中设置调试断点时,为了测试如何使用字段 :remote 和 :days,我必须使用以下代码来获取 :remote 和 : 控制台中的天。

location_params[:ads_attributes]["2"][:remote]

我不明白并且知道如何删除这个["2"] 索引。我想用下面的代码location_params[:ads_attributes][:remote]选择params

这是location_params[:ads_attributes]控制台中的结果

<ActionController::Parameters 
{"0"=><ActionController::Parameters {} permitted: true>, 
"1"=><ActionController::Parameters {"days"=>"12"} permitted: true>,
"2"=><ActionController::Parameters {"remote"=>"1"} permitted: true>}
permitted: true>

我确实在 stackoverflow 上进行了搜索,但找不到针对该索引特定问题的解决方案。

【问题讨论】:

  • 问题出在你的表单上。这就是它发送数据的方式。如果您希望参数具有其他形状,请更改形式。
  • 非常感谢您的帮助

标签: ruby-on-rails ruby


【解决方案1】:

我会建议更好地修复表单视图,在此处添加这些数字:

<%= link_to_add_association "Add another", f, :ads %>
<%= f.fields_for :ads do |ff| %>
      <%= ff.form_group ::remote do |ad| %>
          <%= ad.label :remote %> *
          <%= ad.text_field :remote %>
      <% end %>
      <%= ff.form_group :days do |ad| %>
          <%= ad.label :days %> *
          <%= ad.text_field :days %>
      <% end %>
      <%= link_to_remove_association "remove", ff %>
<% end %>

【讨论】:

  • 非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
相关资源
最近更新 更多