【发布时间】:2011-05-27 17:18:17
【问题描述】:
我正在使用 has many through 关联,以便可以将文章“保存”到多个部分,并且该关系称为位置。在位置表中还有一个“默认”列(布尔值),这允许用户指示哪个部分是默认部分。
以下是模型:
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 %>
到目前为止,我可以很好地保存和更新位置,但我不确定如何将默认字段分配给每个保存的位置。我为每个部分添加了一个单选按钮,因此用户可以选择默认值,但我不确定如何将它们结合在一起。
任何想法都将不胜感激!谢谢。
【问题讨论】:
标签: ruby-on-rails ruby forms ruby-on-rails-3 has-many-through