Ruby on rails 将条目添加到具有多个直通关系的直通表中

Ruby on rails 将条目添加到具有多个直通关系的直通表中,ruby-on-rails,Ruby On Rails,我有一个创建样式的表单。创建样式时,用户还必须为样式选择一些功能 这些功能将预先填充到表单内的多选框中。保存样式时,应使用表单上选定的每个特征的条目(样式id和特征id)更新直通表 我的控制器中有: def new @style = Style.new @style.stylefeatures.build end def create @style = Style.new(params[:style]) @style.stylefeatures.build

我有一个创建样式的表单。创建样式时,用户还必须为样式选择一些功能

这些功能将预先填充到表单内的多选框中。保存样式时,应使用表单上选定的每个特征的条目(样式id和特征id)更新直通表

我的控制器中有:

def new
    @style = Style.new
    @style.stylefeatures.build
end

def create 
    @style = Style.new(params[:style])
    @style.stylefeatures.build
    @style.save
end
…以我的风格模型

  attr_accessible :stylefeatures_attributes
  has_many :stylefeatures
  has_many :features, :through => :stylefeatures, :foreign_key => :feature_id
  accepts_nested_attributes_for :stylefeatures
。。。在我的stylefeature模型中

  belongs_to :style
  belongs_to :feature
  accepts_nested_attributes_for :feature
  attr_accessible :description, :fullname, :name
  has_many :stylefeatures
  has_many :styles, :through => :stylefeatures, :foreign_key => :style_id
。。。在我的特征模型中

  belongs_to :style
  belongs_to :feature
  accepts_nested_attributes_for :feature
  attr_accessible :description, :fullname, :name
  has_many :stylefeatures
  has_many :styles, :through => :stylefeatures, :foreign_key => :style_id
。。。以我的创作形式

<%= m.simple_fields_for :stylefeatures do |p| %>
  <%= p.input :feature_id, :label => "Features", :collection => Feature.all, :input_html => { :multiple => true } %>
<% end %>

“Features”,:collection=>Feature.all,:input_html=>{:multiple=>true}%>
现在,当我保存新样式时,stylefeatures表将更新为相应的Style_id,但有两个无用的条目。第一个是一个数组,其中包含表单中选定的所有特征ID。第二个是一个空白条目,具有适当的样式id,而feature id列中没有任何内容


您是否知道我可能做错了什么,或者如何根据需要将收集到的特性id分散到表中?

在新操作中,仅构建一个stylefeature,因此将仅创建一个特性id为'1,3,45563'(ofc取决于您选择的特性) 第二个是由create操作中的
@style.stylefeatures.build生成的

您可以尝试删除字段,只需使用:feature\u id而不是:feature\u id

<%= p.input :feature_ids, :label => "Features", :collection => @features, :input_html => { :multiple => true } %>
“Features”,:collection=>@Features,:input\u html=>{:multiple=>true}%>

“Features”,:collection=>@Features,:input\u html=>{:multiple=>true}%>

Yuri,谢谢你的帮助。只有一件事,当我尝试你的第一个建议时,我得到以下错误:提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换:从“features”中选择“features”.id,在“features”中的“features”内部连接“stylefeatures”。“id”=“stylefeatures”。“feature\u id”中的“stylefeatures”。“style\u id”为空。当我尝试第二个建议时,我得到一个无方法错误:(f.collection\u复选框:feature\u id、@features、:id、:name和use HABM association如果你不需要rich join tableHey我的问题是外键在我的数据库中被创建为字符串而不是整数。谢谢Yuri,你的代码确实有效。