【问题标题】:Rails 3 - Nested forms with a has many through association with checkboxesRails 3 - 带有 a 的嵌套表单与复选框有很多关联
【发布时间】: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


    【解决方案1】:

    不确定为什么需要单选按钮和复选框。尝试添加 hidden_​​field_tag 和 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>
    

    【讨论】:

    • 感谢您的回复。具有复选框和单选按钮的想法是,对于每个部分,都会显示一个复选框和单选按钮,允许用户使用复选框选择多个部分,并使用单选按钮将其中一个部分设置为默认部分。单选按钮需要共享相同的名称(组),以便只能选择一个。
    猜你喜欢
    • 2014-04-07
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多