如何获得强参数以允许嵌套 fields_for 属性? [英] How can I get strong parameters to permit nested fields_for attributes?

查看:57
本文介绍了如何获得强参数以允许嵌套 fields_for 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有嵌套 fields_for 的表单.我试图允许由该嵌套表单生成的参数,但它们被强参数阻止.我使用的是 rails 4.2.4 和 ruby​​ 2.2.2

I have a form with a nested fields_for. I have attempted to permit the parameters that are generated by that nested form, but they are being blocked by strong parameters. I'm using rails 4.2.4 and ruby 2.2.2

我阅读了一些官方文档:

I've read some official documentation:

我已经阅读了看起来像相关的 SO 帖子:

I've read what looks like relevant SO posts:

我阅读了各种博客文章:

I've read various blog posts:

我想我正在按照他们说的去做,但是我的嵌套属性被强参数拒绝了.我在我的日志中得到了诸如 Unpermitted parameters: __template_row__, 0, 1, 2, 3 之类的东西.

I think I'm following what they say to do, but my nested attributes get rejected by strong parameters. I get things like Unpermitted parameters: __template_row__, 0, 1, 2, 3 in my log.

这是我的代码:

models/enclosure.rb

class Enclosure < ActiveRecord::Base
  has_many :resident_animals, -> { order("year DESC, month DESC") }, dependent: :restrict_with_error
  validates :name, presence: true, uniqueness: {case_sensitive: false}

  accepts_nested_attributes_for :resident_animals, allow_destroy: true, reject_if: :all_blank

  def to_s
    name
   end
end

models/resident_animal.rb

class ResidentAnimal < ActiveRecord::Base
  belongs_to :enclosure

  validates_presence_of :enclosure, :year, :month, :color
  ...
end

controllers/enclosures_controller.rb

class EnclosuresController < ApplicationController
  ...
  def update
    @enclosure = Enclosure.find(params[:id])
    @enclosure.update(enclosure_params)
    respond_with @enclosure
  end

  private

  def enclosure_params
    params.require(:enclosure).permit(:name, :description, resident_animals_attributes: [:year, :month, :color, :id, :_destroy])
  end
end

views/enclosures/_form.html.erb

<p class="field">
  <%= form.label :name %>
  <%= form.text_field :name %>
</p>

<p class="field">
  <%= form.label :description %>
  <%= form.text_area :description %>
</p>

<fieldset>
  <legend>Resident Animals</legend>

  <table id="resident-animal-rows">
    <thead>
      <th>Year <span class="required-field">*</span></th>
      <th>Month <span class="required-field">*</span></th>
      <th>Color <span class="required-field">*</span></th>
      <th>Remove</th>
    </thead>
    <tbody>
      <%= form.fields_for :resident_animals_attributes, ResidentAnimal.new(channel: form.object, year: Date.current.year, month: Date.current.month), index: "__template_row__" do |resident_animal_fields| %>
      <tr class="resident-animal-row row-template">
        <td><%= resident_animal_fields.number_field :year %></td>
        <td><%= resident_animal_fields.select :month, month_options, include_blank: true %></td>
        <td><%= resident_animal_fields.text_field :color %></td>
        <td class="checkbox-cell"><%= resident_animal_fields.check_box :_destroy %></td>
      </tr>
      <% end %>
      <%= form.fields_for :resident_animals do |resident_animal_fields| %>
        <tr class="resident-animal-row">
          <td><%= resident_animal_fields.number_field :year %></td>
          <td><%= resident_animal_fields.select :month, month_options, include_blank: true %></td>
          <td><%= resident_animal_fields.text_field :color %></td>
          <td class="checkbox-cell">
            <%= resident_animal_fields.hidden_field :id %>
            <%= resident_animal_fields.check_box :_destroy %>
          </td>
        </tr>
      <% end %>
    </tbody>
  </table>
  <%= link_to "Add resident animal", "#", class: "resident-animal-row-add" %>
</fieldset>

当我记录我的参数时,它们看起来像:

When I log my parameters they look like:

{"enclosure"=>{"name"=>"Polar Quest", "description"=>"Polar bear attraction", "resident_animals_attributes"=>{"__template_row__"=>{"year"=>"2015", "month"=>"9", "color"=>"", "_destroy"=>"0"}, "0"=>{"year"=>"2005", "month"=>"8", "color"=>"white", "id"=>"1", "_destroy"=>"0"}, "1"=>{"year"=>"2012", "month"=>"7", "color"=>"yellow", "id"=>"2", "_destroy"=>"0"}, "2"=>{"year"=>"2011", "month"=>"3", "color"=>"white", "id"=>"4", "_destroy"=>"0"}, "3"=>{"year"=>"2006", "month"=>"2", "color"=>"yellowish", "id"=>"3", "_destroy"=>"0"}}}, "commit"=>"Update", "id"=>"1"}

调用enclosure_params 返回:

Calling enclosure_params returns:

{"name"=>"Polar Quest", "description"=>"Polar bear attraction", "resident_animals_attributes"=>{}}

我做错了什么?

推荐答案

谢谢!

我将在此处添加您评论中的正确答案,以便此问题有正确答案:

I'm going to add that correct answer from your comment here, just so this question can have a correct answer:

问题在于 .permit 嵌套的哈希,其中包括 ID 作为键和其他属性的哈希作为值是一种特殊情况(很明显,因为它没有匹配 .permit 的典型参数结构.

The problem is that .permit-ing a nested hash that include IDs as the keys and a hash of other attributes as the values is a special case (as is apparent, since it doesn't match the typical argument structure for .permit).

诀窍是:算法检测特殊情况(称为fields_for_style? 因为它是通常由 fields_for 助手提交的参数样式)当且仅当所有键都转换为整数!因此,如果您在键集中有一个非整数值(例如 __template_row__new_record_id),它不会检测特殊情况,而是拒绝每个键在未明确允许的哈希中(对于任何典型的哈希).

The trick is: the algorithm detects the special case (called fields_for_style? because it is the style of params typically submitted by the fields_for helper) if, and only if, all of the keys translate to integers! Therefore, if you have a non-integer value (such as __template_row__ or new_record_id) in the set of keys, it will not detect a special case, and instead reject every key in the hash that is not explicitly permitted (as for any typical hash).

为了解决这个问题,根据原始帖子中的参数结构,您可以简单地删除作为模板行一部分提交的非整数键和属性:

In order to get around this, given the structure of params from the original post, you can simply remove the non-integer key and attributes submitted as part of the template row:

def enclosure_params
  params[:enclosure][:resident_animals_attributes].delete(:__template_row__)
  params.require(:enclosure).permit(...) # (no change from OP)
end

(当然这意味着,您应该确保您的界面不会尝试提交有意义的数据作为模板行的一部分);)

(Of course this means, you should be sure your interface does not try to submit meaningful data as part of your template row) ;)

这篇关于如何获得强参数以允许嵌套 fields_for 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆