从选择字段创建多个嵌套记录

时间:2014-02-03 05:45:59

标签: ruby-on-rails nested-attributes fields-for

需要建议,如何修复在rails中创建多个嵌套记录。

我的代码:

模型

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

在控制器中

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

在视图中

<%= 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 %>

如果我删除:multiple =&gt; true,:size =&gt; 5 条件,单个嵌套记录成功创建, 但是使用:multiple 时会失败并显示错误:Unpermited param feature_id

1 个答案:

答案 0 :(得分:0)

如果其他人偶然发现了这个:

我认为你应该将你的参数更改为:feature_ids,因为你正在寻找多条记录。在控制器和视图中更改它!