Using checkboxes with has_many relation

I have an account with some lines. A line can belong to only one account. This is what my circuit looks like:

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

And my models:

 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 rows (rows already exist in the database) and check the box for each row to associate it with the invoice.

I looked at the HABTM problem, but I don’t think I need it here, the problem is not so complicated. I think the problem is that I want to update Unit # invoice_id while I work on the texture. Can I do this with a nested form or do I need a before_save callback here?

Thanks!

+4
source share
3 answers

The has_many association also added accessor line_ids , which you can create checkboxes for.

If you use simple_form or formtastic , this is incredibly simple:

 <%= 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’s all there is. No nested forms or anything else.

+7
source

Look at Ian's answer. This is definitely the right way, but ... I prefer not to use simple_form or formtastic for this example, so that it is as simple as possible.

I used the Iain HTML output to extract the HTML that I need. This snippet is the same as Iain's answer, without the need for an additional library:

 <% 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 and @invoice.lines... must be extracted to the controller and invoice model, they do not belong to the view. They are used only for brevity.

+14
source

I recommend using the collection_check_boxes helper method:

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

or Haml:

 = collection_check_boxes :invoice, :lines, @lines, :id, :name 
+4
source

All Articles