Unable to select radio buttons using labels in ruby on rails while running through a loop?

感情迁移 提交于 2021-02-08 04:49:34

问题


Here is the code I am writing for RADIO BUTTON in RAILS

<% @Days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] %>
<% @Days.each do |day| %>
<%= f.radio_button :due_day, day, :checked => @group.due_day.eql?(day) %> 
<%= f.label :due_day, day %>
<% end %>

And at HTML I get

<input checked="checked" id="group_due_day_monday" name="group[due_day]" type="radio" value="Monday" /> 
<label for="group_due_day">Monday</label>
.....
.....
<input id="group_due_day_sunday" name="group[due_day]" type="radio" value="Sunday" /> 
<label for="group_due_day">Sunday</label>

but I want it to be like

<input checked="checked" id="group_due_day_monday" name="group[due_day]" type="radio" value="Monday" /> 
<label for="group_due_day_monday">Monday</label>
.....
.....
<input id="group_due_day_sunday" name="group[due_day]" type="radio" value="Sunday" /> 
<label for="group_due_day_sunday">Sunday</label>

So that if the label is clicked RADIO BUTTON gets selected. This can be achieved using

<%= f.radio_button :due_day, day, :checked => @group.due_day.eql?(day) %> 
<%= f.label :due_day_monday, day %>

But this is not good practice in case, if I have a set of USERS says @users. Where I dont know the length of the array and also the users names ??


回答1:


FormHelper label accepts a :value option precisely for this scenario:

<% @Days.each do |day| %>
<%= f.radio_button :due_day, day, :checked => @group.due_day.eql?(day) %> 
<%= f.label :due_day, day, :value => day %>
<% end %>


来源:https://stackoverflow.com/questions/12507257/unable-to-select-radio-buttons-using-labels-in-ruby-on-rails-while-running-throu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!