【问题标题】:Using check boxes with a has_many relationship使用具有 has_many 关系的复选框
【发布时间】:2011-12-03 16:17:43
【问题描述】:

我有一张包含几行的发票。一行只能属于一张发票。这就是我的架构的样子:

create_table "invoices" do |t|
end

create_table "lines" do |t|
  t.integer  "invoice_id"
end

还有我的模特:

class Invoice < ActiveRecord::Base
  has_many :lines
end

class Line < ActiveRecord::Base
  belongs_to :invoice
end

现在,在创建(或编辑)发票时,我想显示一个包含所有可能行的列表(数据库中已经存在这些行),并为每行提供一个复选框以将其与发票链接。

我查看了 HABTM 问题,但我认为这不是我需要的,问题没有那么复杂。我认为问题是我想在处理发票时更新 Unit#invoice_id。我可以使用嵌套表单执行此操作还是需要 before_save 回调?

谢谢!

【问题讨论】:

    标签: ruby-on-rails activerecord checkbox


    【解决方案1】:

    我推荐使用collection_check_boxes 辅助方法:

    <%= collection_check_boxes :invoice, :lines, @lines, :id, :name %>
    

    或哈姆:

    = collection_check_boxes :invoice, :lines, @lines, :id, :name
    

    【讨论】:

      【解决方案2】:

      看看伊恩的回答。这绝对是正确的方法,但是...我不想在此示例中使用 simple_formformtastic,以使其尽可能简单。

      我使用 Iain 的 HTML 输出来提取我需要的 HTML。这个 sn-p 与 Iain 的答案相同,不需要额外的库:

      <% Line.all.each do |line| %>
        <%= hidden_field_tag "invoice[line_ids][]" %>
        <%= check_box_tag "invoice[line_ids][]", line.id, @invoice.lines.include?(line), :id => "invoice_line_ids_#{line.id}" %>
      <% end %>
      

      PS:Line.all@invoice.lines... 应该被提取到控制器和发票模型中,它们不属于视图。它们只是为了简洁起见。

      【讨论】:

        【解决方案3】:

        has_many 关联还会添加访问器 line_ids,您可以为其创建复选框。

        如果您使用 simple_formformtastic,这非常简单:

        <%= f.input :line_ids, :as => :check_boxes %>
        

        这将创建这样的东西:

        <span>
          <input name="invoice[line_ids][]" type="hidden" value="" />
          <input checked="checked" class="check_boxes optional" id="invoice_line_ids_1" name="invoice[line_ids][]" type="checkbox" value="1" />
          <label class="collection_check_boxes" for="invoice_line_ids_1">Line Name 1</label>
        </span>
        
        <span>
          <input name="invoice[line_ids][]" type="hidden" value="" />
          <input checked="checked" class="check_boxes optional" id="invoice_line_ids_2" name="invoice[line_ids][]" type="checkbox" value="2" />
          <label class="collection_check_boxes" for="invoice_line_ids_2">Line Name 2</label>
        </span>
        

        这就是它的全部。不需要嵌套表单或其他任何东西。

        【讨论】:

        • 这件事令人讨厌的是生成的空隐藏字段。它没用,并且干扰了这个助手的目的(用于关联)。每次提交时,它都会在数组中添加一个空字符串 ''。你们有谁知道如何绕过它,但仍然使用这个助手?
        • 也许你可以试试 - :check_boxes include_blank => false %>
        猜你喜欢
        • 2017-01-23
        • 1970-01-01
        • 1970-01-01
        • 2021-02-18
        • 1970-01-01
        • 2012-02-01
        • 2013-04-26
        • 2013-05-12
        • 1970-01-01
        相关资源
        最近更新 更多