在一个直通表中添加条目有很多关系

时间:2012-05-21 09:47:42

标签: ruby-on-rails

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

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

...以及我的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

...并以我的创建形式

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

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

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

1 个答案:

答案 0 :(得分:0)

在新动作中你只构建一个stylefeature,所以只有一个将使用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 } %>
相关问题