Cannot display label for multiple checkboxes in Rails 4.2 and Bootstrap 3

For some reason the following code will not show the correct labels ('Credit Card', 'Paypal', 'Direct Deposit'):

= form_for @merchant, layout: :horizontal do |f|
  = f.check_box :payment_accepted, { :multiple => true }, 'Credit Card', nil
  = f.check_box :payment_accepted, { :multiple => true }, 'Paypal', nil
  = f.check_box :payment_accepted, { :multiple => true }, 'Direct Deposit', nil
  = f.submit 'Save Changes', :class => 'btn btn-primary'

It will show 'Payment accepted' as labels for all 3 checkboxes

Wrapping a checkbox within a label in a block:

= f.label :payment_accepted, 'Credit Card' do
  = f.check_box :payment_accepted, { :multiple => true }, 'Credit Card', nil

Has no effect.

Any help will be appreciated.

Upvotes: 0

Views: 310

Answers (2)

It took me a while to figure this out, and it turned out to be obvious. Here's the thing:

When using the Rails form Helpers and Bootstrap, the f.checkbox helper will generate a label by default. There is no way to override this behaviour other than subclassing the form helper function (overkill?)

So adding an f.label will only duplicate the labels and has no effect on the label generated by the f.checkbox helper.

The solution is to customize the actual label the f.checkbox helper function generates, since it turns out it takes a (seemingly undocumented) :label parameter in the options group.

So this finally did the trick:

=f.check_box :payment_accepted, { :multiple => true, :label => 'Credit Card'}, 'Credit Card', nil

Hopes it saves someone hours of pulling out their hair (like me).

Upvotes: 0

Bryan Saxon
Bryan Saxon

Reputation: 663

It is actually a common misconception that you need to use the label method for form checkboxes. You should be able to use the default bootstrap syntax.

http://getbootstrap.com/css/#forms-example

  .checkbox
    %label
      = f.check_box :payment_accepted, { :multiple => true }, 'Credit Card', nil
      Credit Card

Upvotes: 2

Related Questions