更短的方式 - 单选按钮

时间:2021-08-11 18:03:21

There has to be a more efficient way in Rails of doing this:

在Rails中必须有一种更有效的方法:

<p>
    <%= f.label :level %>
    <%= f.radio_button :level, "0" %> <%= f.label :level, 0 %>
    <%= f.radio_button :level, "1" %> <%= f.label :level, 1 %>
    <%= f.radio_button :level, "2" %> <%= f.label :level, 2 %>
    <%= f.radio_button :level, "3" %> <%= f.label :level, 3 %>
    <%= f.radio_button :level, "4" %> <%= f.label :level, 4 %>
    <%= f.radio_button :level, "5" %> <%= f.label :level, 5 %>
</p>

The db has a column "level" that can have values from 0-5. I need the current value to be displayed in HTML (ie checked="checked") as this code does. There has to be a more succinct way in Rails of doing this. Any takers?

db具有列“级别”,其值可以是0-5。我需要将当前值显示在HTML中(即checked =“checked”),就像这段代码一样。在Rails中必须有一个更简洁的方法来做到这一点。任何接受者?

1 个解决方案

#1


It's easy enough with a loop:

循环很容易:

<p>
    <%= f.label :level %>
    <% 0.upto(5) do |level| %>
      <%= f.radio_button :level, level.to_s %> <%= f.label :level, level %>
    <% end %>
</p>

#1


It's easy enough with a loop:

循环很容易:

<p>
    <%= f.label :level %>
    <% 0.upto(5) do |level| %>
      <%= f.radio_button :level, level.to_s %> <%= f.label :level, level %>
    <% end %>
</p>