Home > database >  Constructing a Label for a Form inside a Loop
Constructing a Label for a Form inside a Loop

Time:10-14

I have the following code for my index.html.erb:

<%= form_with do |form| %>
  <% @electives.each do |elective| %>
    <div>
      <%= elective.name %>
    </div>
    <% elective.courses.each do |course| %>
      <div>
        <%= form.radio_button :elective.id, course.id %>
        <%= form.label %>
      </div>
    <% end %>
  <% end %>
<% end %>

I want to construct the label for the radio button, but I don't know how to specify the first argument to it. I am following Rails Guides, and I see that it should have the form: first argument to radio_button _ second argument to radio_button.

So, in my case, it should be :elective.id_course.id. But, I don't know how to enter it correctly.

Any help would be appreciated. Thank you.

CodePudding user response:

You should pass the :value option, which is designed to target labels for radio_button tags:

<% elective.courses.each do |course| %>
  <div>
    <%= form.radio_button :elective.id, course.id %>
    <%= form.label :elective.id, course.id, :value: course.id %>
  </div>
<% end %>

See more on ActionView::Helpers::FormHelper#label

  • Related