开发者

Rails 3 - Nested forms with a has many through association with checkboxes

开发者 https://www.devze.com 2023-01-31 19:36 出处:网络
I am using a has many through association so that an article can be \'saved\' to many sections and that relation is called a location. In the locations table there is also a \'default\' column (boolea

I am using a has many through association so that an article can be 'saved' to many sections and that relation is called a location. In the locations table there is also a 'default' column (boolean), this allows the user to indicate which section is the default one.

Here are the models:

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

So in my view:

<%= 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, @art开发者_运维技巧icle.section_ids.include?(section.id), :id => dom_id(section) %><%= label_tag dom_id(section), section.name %></li>
      <% end %>
     </ul>
   </p>
...
<% end %>

So far I can save and update the locations fine but I'm not sure how to assign the default field to each location saved. I have added a radio button for each section so the user can select the default but I'm not sure how to tie it all together.

Any ideas will be really appreciated! Thanks.


Not sure why you need both a radio button and check box. Try adding a hidden_field_tag along with a check_box_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

精彩评论

暂无评论...
验证码 换一张
取 消