强大的参数has_many通过

时间:2014-12-30 13:56:58

标签: ruby-on-rails

试图找出setter无法解决的原因:

class Company < ActiveRecord::Base
  has_many :memberships 
  has_many :users, :through => :memberships, dependent: :destroy

end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :company

  validates_presence_of :user
  validates_presence_of :company

end

class User < ActiveRecord::Base
  has_many :memberships
  has_many :companies, :through => :memberships, dependent: :destroy
  accepts_nested_attributes_for :companies
end

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% @user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.fields_for :company do |ff|%>
      <%= ff.label :name %><br>
      <%= ff.text_field :name %>
    <% end %>
  </div>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

# Never trust parameters from the scary internet, only allow the white list through.
def user_params
  params.require(:user).permit(:name, companies_attributes:[:name])
end

当我这样做时它会起作用:

# Never trust parameters from the scary internet, only allow the white list through.
def user_params
  params.require(:user).permit(:name, company:[:name])
end

所以对我而言,目前还不是很清楚,因为文档中说,当accept_nested_attributes_for:公司

时,setter companies_attributes被终止了

1 个答案:

答案 0 :(得分:2)

fields_foraccepts_nested_attributes_for一起使用时,他们需要匹配。见http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

您有accepts_nested_attributes_for :companiesf.fields_for :company因此断开连接。

因此,请尝试将表单更改为包含

<div class="field">
    <%= f.fields_for :companies do |ff|%>
      <%= ff.label :name %><br>
      <%= ff.text_field :name %>
    <% end %>
  </div>

和你的user_params方法

def user_params
  params.require(:user).permit(:name, companies_attributes:[:name])
end

哪个应该会在companies_attributes和原始user_params方法下填充它们。因为fields_for应该生成user[companies_attributes[id][name]],因为user has_many companies(你想在列表中包含多个公司吗?)