使用has_many的Rails嵌套形式:通过

时间:2018-12-09 18:48:29

标签: ruby-on-rails ruby model-view-controller null accepts-nested-attributes

我有3个模型,产品模型通过product_categories模型与公司模型建立了联系。我想创建一个表格,可以在公司表格中添加带有类别的产品。

固定模型

class Firm < ApplicationRecord
 has_many :product_categories
 has_many :products, through: :product_categories
 accepts_nested_attributes_for :product_categories
end

产品型号

class Product < ApplicationRecord
 has_many :product_categories
 has_many :firms, through: :product_categories
 has_many :variants, class_name: 'ProductVariant'
end

ProductCategory

class ProductCategory < ApplicationRecord
 belongs_to :product
 belongs_to :firm
 accepts_nested_attributes_for :product
end

这是我为公司创建表格的样子

<%= form_with(model: @firm, local: true) do |form| %>
  firm.fields...
  <%= form.fields_for :product_categories do |prod_c_f| %>
   product_category.fields...
     <%= prod_c_f.fields_for :product do |prod_f| %>
      product.fields...
     <% end %>
  <% end %>
  <%= form.submit "Create Firm", class: 'btn btn-primary 
  btn-block ' %>
<% end %>

这是我的控制器

def create
@firm = Firm.new

@firm.product_categories.build.build_product
 respond_to do |format|
  if @firm.save
   format.html { redirect_to firms_path, notice: '...' }
  else
  format.html { render :new }
  end
 end
end

这是参数

params.require(:firm).permit(:title, 
product_categories_attributes:[ product_attributes: 
[:title, :price, :description]])

该表单不显示:

And the form doesn't display

0 个答案:

没有答案