0

スタイルを作成するためのフォームがあります。スタイルを作成するとき、ユーザーはスタイルのいくつかの機能も選択する必要があります。

機能は、フォーム内の複数選択ボックスに事前に入力されています。スタイルが保存されると、フォームで選択された各機能のエントリ (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 %>

新しいスタイルを保存すると、stylefeatures テーブルが適切な style_id で更新されますが、2 つの役に立たないエントリがあります。1 つ目は、フォームで選択されたすべての機能 ID の配列です。2 つ目は、適切な style_id を持つ空白のエントリで、feature_id 列には何もありません。

私が間違っている可能性があること、または収集した feature_id を必要に応じてテーブルに分散する方法の手がかりはありますか?

4

1 に答える 1

0

@style.stylefeatures.build新しいアクションでは、stylefeature を 1 つだけ作成するため、feature_id = '1,3,45,563' で作成されるのは 1 つだけです (ofc は、選択した機能によって異なります) 。

あなたは fields_for を削除して、単に :feature_id の代わりに :feature_ids を使用することができます

<%= 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 } %>
于 2012-05-21T10:43:05.187 に答える