Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple column names/custom label in Rails collection_check_boxes

I have a form_for in Rails that uses the collection_check_boxes method for an array of parts that get listed as check boxes. I want the label of the checkbox to be a composite of two methods so that each part's checkbox is labeled with it's name and it's SKU number:

my form code:

<%= collection_check_boxes(:service, :part_ids, @parts_list, :id, :sku, {}, {checked: true}) %>

this works perfectly to create a list of check boxes. But each label is only the :sku since I can only pass it one method for the label. Does anyone know of a way to create a custom label for these? I have read the api docs and it mentions using a do |b| ... end block but doesn't explain how to use it or why.

like image 917
Beartech Avatar asked Feb 22 '14 21:02

Beartech


2 Answers

Here is the modified form code:

<%= collection_check_boxes(:service, :part_ids, @parts_list, :id, :sku, {}, {checked: true}) do |b| 
  b.label { b.check_box + b.object.name + " " + b.object.sku} 
end %>

NOTE: b.object.name #### Assuming that name is field name in your model b.object.sku #### Replace with b.object.sku.to_s if sku is numeric field.

like image 124
Kirti Thorat Avatar answered Oct 14 '22 06:10

Kirti Thorat


You could define a custom field in your model:

def cb_label
    "#{name} #{sku}"
end

and in the collection

<%= collection_check_boxes(:service, :part_ids, @parts_list, :id, :cb_label, {}, {checked: true}) %>
like image 33
Ruby Racer Avatar answered Oct 14 '22 07:10

Ruby Racer