Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to many relationship with nested forms in Rails 4 - Unpermitted parameters error

I am attempting to make the relationship in the Products controller through the Categorizations model to the ClothingSize model. I am getting a "Unpermitted parameters: clothing_size" error and the relationship is not ever made as a result. I think there is something wrong with the nested forms in the view as I cannot get the "Size" field to appear unless the symbol is singular shown below. I think that may be pointing to another problem.

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

Models

Products

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

Categorizations

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

Controller for Products

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

View

<%= 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 %>
like image 350
gjarnos Avatar asked Sep 03 '25 15:09

gjarnos


1 Answers

In your view you have :clothing_size (singular) but in your product_params method you have :clothing_sizes (plural). Because your Product model has_many :clothing_sizes, you want it to be plural in your view.

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

In addition, you'll want to build a clothing_size for your product in your controller, and permit :clothing_sizes_attributes rather than clothing sizes in your product_params method. (I'd separate your new and product_params methods, making product_params private, but that's just me.)

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
like image 144
Joe Kennedy Avatar answered Sep 05 '25 04:09

Joe Kennedy