2010-12-18 18 views
2

私はmany through throughアソシエーションを使用しているので、記事を多くのセクションに保存でき、そのリレーションをロケーションといいます。場所テーブルには「デフォルト」の列(ブール値)もあります。これにより、ユーザーはどのセクションがデフォルトのものであるかを示すことができます。私の見解ではそうRails 3 - aを含むネストされたフォームは、チェックボックスとの関連が多い

class Article < ActiveRecord::Base 
    has_many :locations 
    has_many :sections, :through => :locations 

    def default_location 
    self.sections.where('locations.default = 1').first 
    end 
end 

class Location < ActiveRecord::Base 
    belongs_to :article 
    belongs_to :section 
end 

class Section < ActiveRecord::Base 
    has_many :locations 
    has_many :articles, :through => :locations 
end 

:ここ

はモデルでありこれまで

<%= form_for(@article) do |f| %> 
... 
    <p class="field"> 
    <h3>Locations</h3> 
    <ul> 
     <% @sections.each do |section| %> 
     <li><%= radio_button_tag ???, section.id, :checked => @article.default_location == section %> <%= check_box_tag 'article[section_ids][]', section.id, @article.section_ids.include?(section.id), :id => dom_id(section) %><%= label_tag dom_id(section), section.name %></li> 
     <% end %> 
    </ul> 
    </p> 
... 
<% end %> 

私は保存し、細かい場所を更新することができますが、私はデフォルトのフィールドを割り当てるするかどうかはわかりません保存された各場所に移動します。ユーザーがデフォルトを選択できるように、各セクションにラジオボタンを追加しましたが、すべての方法を結び付ける方法がわかりません。

アイデアは本当にありがとう!ありがとう。

答えて

1

ラジオボタンとチェックボックスの両方が必要な理由がわかりません。 check_box_tagと一緒にhidden_​​field_tagを追加してみてください:

<p class="field"> 
    <h3>Locations</h3> 
    <%= hidden_field_tag "article[section_ids][]", "" %> 
    <ul> 
     <% @sections.each do |section| %> 
     <li> 
      <%= check_box_tag :section_ids, section.id, @article.section_ids.include?(section.id), :id => dom_id(section), :name => 'article[section_ids][]' %> 
      <%= label_tag dom_id(section), section.name %> 
     </li> 
     <% end %> 
    </ul> 
    </p> 
+0

お返事ありがとうございます。チェックボックスとラジオボタンの背後にあるアイデアは、チェックボックスとラジオボタンが表示され、チェックボックスで複数のセクションを選択できるようになり、ラジオボタンを使用してセクションの1つをデフォルトセクションとして設定することができます。ラジオボタンは同じ名前(グループ)を共有する必要があるため、1つだけを選択できます。 – Mike

関連する問題