嵌套参数的奇怪行为

Weird behavior with nested params

我在使用嵌套参数时遇到了这种奇怪的行为。 当我尝试保存表格时,它显示 Unpermitted parameter: organization_type

对于我的组织类型,我只有一个模型,但我认为这不应该是问题,因为根据我的理解,属性是在用户控制器中处理的

我尝试在表单和控制器白名单中都将属性设置为 organization_type(单数),但这不起作用。

但是,在表单中,如果我有 :organization_types 字段将不会显示。

对此我真的很纳闷

快速回顾一下:

用户模型

class User < ActiveRecord::Base
  has_many :events
  has_many :organization_types
  accepts_nested_attributes_for :organization_types
end

组织类型模型

class OrganizationType < ActiveRecord::Base
  belongs_to :user
  ORG_TYPES = ['health', 'non-profit', 'foo', 'bar']
end

用户控制器

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  before_filter :authenticate_user!

  ...

  def user_params
      params.require(:user).permit(:name, ..., organization_types_attributes: [:id, :user_id, :org_type, '_destroy'])
  end

用户表单

<%= form_for(@user) do |f| %>
  ...
  <div class="field">
    <%= f.label :organization_type %><br>
    <%= f.fields_for :organization_type do |builder| %>
      <%= builder.select :org_type, options_for_select(OrganizationType::ORG_TYPES) %><br/>
    <% end %>
  </div>
<% end %>

在你的嵌套形式中应该是:organization_types

<%= f.fields_for :organization_types do |builder| %>
  <%= builder.select :org_type, options_for_select(OrganizationType::ORG_TYPES) %><br/>
<% end %>

您发现表单不显示复数形式 organization_types 的原因是,如果用户没有 organization_types,Rails 将不会呈现表单中的嵌套属性然而。我会查看关于 nested forms 的非常有用的 Rails 指南,第 9.2 节。引用该来源,它使用 has_many 地址和 accepts_nested_attributes_for 地址的 Person 对象的示例:

When an association accepts nested attributes fields_for renders its block once for every element of the association. In particular, if a person has no addresses it renders nothing. A common pattern is for the controller to build one or more empty children so that at least one set of fields is shown to the user. The example below would result in 2 sets of address fields being rendered on the new person form...

指南中的示例,适用于您的控制器:

def new   
  @user = User.new
  2.times { @user.organization_types.build}
end

看看是否有帮助...