使用复选框以的has_many关系 [英] Using check boxes with a has_many relationship
问题描述
我有一些行的发票。 A线只能属于一个发票。这是我的模式是这样的:
I have an invoice with some lines. A line can only belong to one invoice. This is how my schema looks like:
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
现在,创建(或编辑)的发票我想告诉所有可能的行列表(行已经在数据库中存在),并有一个复选框每一行与发票联系起来的时候。
Now, when creating (or editing) an invoice I would like to show a list with all possible lines (the lines already exist in the database) and have a check box for each line to link it with the invoice.
我有一个看HABTM问题,但我不认为这就是我需要在这里,问题并不复杂。我认为这个问题是我想更新单元#INVOICE_ID而我工作的发票。我能做到这一点的,嵌套表格还是我在这里需要一个before_save回调?
I had a look at the HABTM problem but I don't think that's what I need here, the problem isn't as complex. I think the problem is me wanting to update the Unit#invoice_id while I am working on the invoice. Can I do this with a nested form or do I need a before_save callback here?
谢谢!
推荐答案
一个的has_many协会还增加了访问 line_ids
,您可以创建复选框。
A has_many association also adds the accessor line_ids
, which you can create check boxes for.
如果您使用的是 simple_form
或 formtastic
这是令人难以置信的简单:
If you're using simple_form
or formtastic
it's incredibly easy:
<%= f.input :line_ids, :as => :check_boxes %>
这将创造这样的事情:
Which will create something like this:
<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>
这是所有有给它。没有嵌套的表格或其他任何需要的。
And that is all there is to it. No nested forms or anything else needed.
这篇关于使用复选框以的has_many关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!