ruby on rails – There has got to be a better way of doing this radio logic – Education Career Blog

I have this form and a yes or no radio choice. The get_request_ids(song) basically gives me the ids i need.

<% form_tag '/somewhere' do -%>
  <%  'yes', 'no' .each do |status| %>
    <%= radio_button_tag "group#{get_request_ids(song)}", "#{status}#{get_request_ids(song)}" %>
    <%= status.humanize %>
  <% end %>
 <tr><td><%= submit_tag 'Save' %></td></tr>
<% end %>

The html looks like this

<input id="group_1,2_yes12" name="group1,2" value="yes1,2" type="radio">
<input id="group_1,2_no12" name="group1,2" value="no1,2" type="radio">

<input id="group_3,6,7_yes367" name="group3,6,7" value="yes3,6,7" type="radio">
<input id="group_3,6,7_no367" name="group3,6,7" value="no3,6,7" type="radio">

the params looks like this

 group"=>{"1,2"=>"yes1,2", "3,6,7"=>"no3,6,7"}

i can parse this to get the yes requests and the no request but there has got to be a better way…I feel like this is a hack


It’s not entirely clear to me what you’re trying to do, but there are two thing I notice right off the bat that look unnecessary:

  • The ids are already in the parameter name, no need to include them in the value as well.
  • You have a “group” array in the parameter name, when it looks like you actually want a hash.

So, the radio_button_tag link can be simplified to this:

<%= radio_button_tag "group#{get_request_ids(song)}", status %>

Which would simplify the group param to this:

"group"=>{"1,2"=>"yes", "3,6,7"=>"no"}

That gives the same information, in a much more simplified and accessible form. It may not even need any extra parsing at all.

But without some more context, it’s hard to say exactly what the best way to implement this would be. If you supply some more details about what you’re doing, you might get a better response.

Leave a Comment