Rails 4中嵌套表单的多对多关系-不允许的参数错误



我试图通过Categorizations模型将Products控制器中的关系设置为ClothingSize模型。我得到了一个"不允许的参数:clothing_size"的错误和关系从来没有作为结果。我认为视图中嵌套的表单有问题,因为我不能得到"大小"字段出现,除非符号是单数如下所示。我想这可能指向另一个问题。

<%= form_for(@product) do |f| %>
      <%= f.fields_for :clothing_size do |cs| %> 

模型

产品
class Product < ActiveRecord::Base
  has_many :categorizations
  has_many :clothing_sizes, through: :categorizations
  accepts_nested_attributes_for :categorizations
end

分类

class Categorization < ActiveRecord::Base
  belongs_to :product
  belongs_to :clothing_size
  accepts_nested_attributes_for :clothing_size
end

ClothingSizes

class ClothingSize < ActiveRecord::Base
  has_many :categorizations
  has_many :products, through: :categorizations
  accepts_nested_attributes_for :categorizations
end

产品控制器

def new
  @product = Product.new
  test = @product.categorizations.build

  def product_params
        params.require(:product).permit(:title, :description, :image_url, :image_url2, :price, :quantity, :color, :clothing_sizes => [:sizes, :clothing_size_id])
  end
end
视图

<%= form_for(@product) do |f| %>
  <%= f.fields_for :clothing_size do |cs| %>
    <div class="field">
      <%= cs.label :sizes, "Sizes" %><br>
      <%= cs.text_field :sizes  %>
    </div>
  <% end %>
<% end %>

在您的视图中,您有:clothing_size(单数),但在您的product_params方法中,您有:clothing_sizes(复数)。因为您的Product模型has_many :clothing_sizes,您希望它在您的视图中是复数。

<%= form_for(@product) do |f| %>
  <%= f.fields_for :clothing_sizes do |cs| %>

此外,您将希望在控制器中为product构建clothing_size,并在product_params方法中允许:clothing_sizes_attributes而不是clothing大小。(我会分开你的newproduct_params方法,使product_params私有,但这只是我。)

def new
  @product = Product.new
  @clothing_size = @product.clothing_sizes.build
end
private
  def product_params
    params.require(:product).permit(:title, :description, :image_url, :image_url2, :price, :quantity, :color, :clothing_sizes_attributes => [:sizes, :clothing_size_id])
  end

最新更新