Cim*_*imm 4 checkbox activerecord ruby-on-rails
我有一些行发票.一行只能属于一张发票.这就是我的架构的样子:
create_table "invoices" do |t|
end
create_table "lines" do |t|
t.integer "invoice_id"
end
Run Code Online (Sandbox Code Playgroud)
我的模特:
class Invoice < ActiveRecord::Base
has_many :lines
end
class Line < ActiveRecord::Base
belongs_to :invoice
end
Run Code Online (Sandbox Code Playgroud)
现在,在创建(或编辑)发票时,我想显示一个包含所有可能行的列表(数据库中已经存在的行),并且每行都有一个复选框,用于将其与发票链接.
我看了一下HABTM问题,但我认为这不是我需要的,问题并不复杂.我认为问题是我想在发票时更新Unit#invoice_id.我可以使用嵌套表单执行此操作,还是需要在此处使用before_save回调?
谢谢!
Cim*_*imm 14
看看Iain的回答.这绝对是正确的选择,但是......我宁愿不使用simple_form或者formtastic为了这个例子来保持尽可能简单.
我使用Iain的HTML输出来提取我需要的HTML.这个片段与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 %>
Run Code Online (Sandbox Code Playgroud)
PS:在Line.all和@invoice.lines...应被提取到控制器和发票的模式,他们不认为属于.它们仅用于简洁起见.
has_many关联还添加了访问者line_ids,您可以为其创建复选框.
如果您正在使用simple_form或formtastic非常容易:
<%= f.input :line_ids, :as => :check_boxes %>
Run Code Online (Sandbox Code Playgroud)
这将创建这样的东西:
<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>
Run Code Online (Sandbox Code Playgroud)
这就是它的全部.没有嵌套表格或任何其他需要.