0

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:

And the form doesn't display

kenlukas
  • 3,616
  • 9
  • 25
  • 36
  • Show us your firms_controller.rb. I think you need to add @firm.product_categories.build in `new` action and probably similarily with `@product_categories.products.build` in `new`action. That's what I do in case of nested attributes. – jedi Dec 09 '18 at 20:32
  • You can also inspect what params you are sending from the form by putting `binding.pry` into your `FirmsController#create` action to debug it. – jedi Dec 09 '18 at 20:38

0 Answers0