I have 3 models, the product model has a connection to the firm model through the product_categories model. I want to create a form where I can add product with their category, within the firm form.
Firm model
class Firm < ApplicationRecord
has_many :product_categories
has_many :products, through: :product_categories
accepts_nested_attributes_for :product_categories
end
Product model
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
This is how my create form for the firm looks like
<%= 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 %>
And this is my controller
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
This are the params
params.require(:firm).permit(:title,
product_categories_attributes:[ product_attributes:
[:title, :price, :description]])
And the form doesn't display: