将条目添加到 中的直通表具有许多直通关系



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

这些功能预填充到表单内的多选框中。保存样式时,应使用在表单上选择的每个要素的条目(带有style_id和feature_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

。在我的风格特征模型中

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

现在,当我保存新样式时,样式特征表已使用适当的style_id进行更新,但有两个无用的条目。第一个是包含表单中选择的所有功能 ID 的数组。第二个是空白条目,其中包含适当的style_id,feature_id列中没有任何内容。

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

在新操作中,您只构建一个样式功能,因此只会创建一个feature_id = '1,3,45,563' (ofc 取决于您选择的功能(第二个由创建操作中的@style.stylefeatures.build生成

您可以尝试删除fields_for,只需使用 :feature_ids 而不是 :feature_id

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

<%= input_tag "style[feature_ids][]" , :label => "Features", :collection => @features, :input_html => { :multiple => true } %>

最新更新