【问题标题】:Creating multiple nested records from select field从选择字段创建多个嵌套记录
【发布时间】:2014-02-03 05:45:58
【问题描述】:

需要建议,如何解决在 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 => true, :size =>5 条件,则成功创建单个嵌套记录, 但使用 :multiple 失败并出现错误:Unpermited param feature_id

【问题讨论】:

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


    【解决方案1】:

    如果其他人偶然发现:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 2020-12-22
      • 2018-06-23
      • 1970-01-01
      相关资源
      最近更新 更多