Rails has a form helper f.collection_radio_buttons
which operates very similar to the f.collection_select
form helper.
However, f.colleciton_radio_buttons
only works on collections of objects and doesn't work with a simple array.
As an example, I can have:
<%= f.select :attribute, ["First", "Second"] %>
But there isn't any:
<%= f.radio_buttons :attribute, ["First", "Second"] %>
So to make f.collection_radio_buttons
work with a simple array I have to do:
<%= f.collection_radio _buttons :attribute, ["First", "Second"], :to_s, :to_s %>
This "works" but it seems very hacky. Is there a cleaner way to reference the value of an array instead of calling .to_s
on it?
Maybe this is an old post but if it is helpful for somebody else then here it is. Now in 2019, I'm working with Rails 5 application and I have a form where I had to show two radio buttons for a given attribute.
I a helper method I have:
def get_company_segments
company = current_user.branch.company
[
[company.various_segment_fee, 'various', 'Varios'],
[company.metal_segment_fee, 'metal', 'Metal']
]
end
Output:
#=> [["12.6", "various", "Varios"], ["10", "metal", "Metal"]]
Then in my form view I have something like:
<%= form.collection_radio_buttons(:segment, get_company_segments, :second, :last) do |segment| %>
<div class="form-check form-check-inline">
<%= segment.radio_button(class: 'form-check-input', id: "agreement_segment_#{segment.object.second}" %>
<%= segment.label(class: 'form-check-label', for: "agreement_segment_#{segment.object.second}") %>
</div>
<%- end %>
And it renders something like this:
And the HTML looks like this:
<div class="form-check custom-radio form-check-inline">
<input class="form-check-input" id="agreement_segment_various" data-fee="12.6" type="radio" value="various" name="agreement[segment]">
<label class="form-check-label" for="agreement_segment_various">Varios</label>
</div>
<div class="form-check custom-radio form-check-inline">
<input class="form-check-input" id="agreement_segment_metal" data-fee="10" type="radio" value="metal" name="agreement[segment]">
<label class="form-check-label" for="agreement_segment_metal">Metal</label>
</div>
I hope it could be a good reference for anyone else. 👻
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With