Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails forms using collection_radio_buttons on array instead of objects

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?

like image 273
Dan L Avatar asked Oct 29 '22 17:10

Dan L


1 Answers

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:

enter image description here

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. 👻

like image 142
alexventuraio Avatar answered Nov 15 '22 05:11

alexventuraio