user3264576
user3264576

Reputation: 21

Creating multiple nested records from select field

Need advise, how to fix creating multiple nested records in rails.

My code:

Models

class Category < ActiveRecord::Base
  has_many :fcatalogs
  has_many :features, :through => :fcatalogs
  accepts_nested_attributes_for :fcatalogs
end

class Feature < ActiveRecord::Base
  has_many :fcatalogs
  has_many :categories, :through => :fcatalogs
  accepts_nested_attributes_for :fcatalogs
end

class Fcatalog < ActiveRecord::Base
  self.table_name = 'categories_features'

  belongs_to :category
  belongs_to :feature
end

In controller

def new
  @category = Category.new
    @category.fcatalogs.build
end

def create
  @category = Category.new(category_params)

  respond_to do |format|
    if @category.save
      format.html { redirect_to [:admin, @category], notice: category_params  } #'Category was successfully created.'
      format.json { render action: 'show', status: :created, location: @category }
    else
      format.html { render action: 'new' }
      format.json { render json: @category.errors, status: :unprocessable_entity }
    end
  end
end


# Never trust parameters from the scary internet, only allow the white list through.
  def category_params
    params.require(:category).permit(:parent_id, :name, :description, :url, :image, :position, :visible, :meta_title, :meta_keywords, :meta_description,
                                     :fcatalogs_attributes: [:feature_id])
  end

In view

<%= f.fields_for :fcatalogs do |builder| %>
  <%= builder.label :feature_id, 'Feature' %>
  <%= builder.collection_select(:feature_id, Feature.all, :id, :name, {}, {:multiple => true, :size => 5}) %>
<% end %>

If i remove :multiple => true, :size =>5 condition, single nested record successfully creates, but with :multiple it fails with error: Unpermited param feature_id

Upvotes: 2

Views: 367

Answers (1)

Wouter Ronteltap
Wouter Ronteltap

Reputation: 100

If someone else stumbles upon this:

I think you should change your params to :feature_ids, since you're looking for multiple records. Change it in the controller AND in the view!

Upvotes: 1

Related Questions