如何使用 ERB 将 class 添加到 select 下拉循环

How to add a class to a select dropdown loop using ERB

我有以下循环使用 ERB 创建 select 下拉列表。它工作正常。

  <%= f.select(:player_id) do %>
    <% @players.each do |p| %>
      <%= content_tag(:option, "#{p.first_name} #{p.last_name}", value: p.id) %>
    <% end %>
  <% end %>

我的问题是如何将 class 添加到 select 元素?

我尝试了以下方法:

<%= f.select(:player_id), class: "form-control" do %>
    <% @players.each do |p| %>
      <%= content_tag(:option, "#{p.first_name} #{p.last_name}", value: p.id) %>
    <% end %>
<% end %>

<%= f.select(:player_id), { class: "form-control" } do %>
    <% @players.each do |p| %>
      <%= content_tag(:option, "#{p.first_name} #{p.last_name}", value: p.id) %>
    <% end %>
<% end %>

我见过与此类似的问题,但是 none 使用与上面示例类似的循环。

这应该适合你。

<%= f.select :player_id, options_for_select( @players.collect { |player| ["#{player.first_name} #{player.last_name}", player.id] } ), class: 'form-control' %>

这就是我最后做的事情:

<%= f.select :player_id, options_for_select( @players.collect { |player| ["#{player.first_name} #{player.last_name}", player.id] } ), {}, { class: 'form-control' } %>

我认为您的代码有问题 f.select(:player_id)

您正在调用 select 方法,只有一个参数 :player_id。所以你可以像这样传递其他选项。

<%= f.select :player_id, class: "form-control" do %>
  <% @players.each do |p| %>
    <%= content_tag(:option, "#{p.first_name} #{p.last_name}", value: p.id) %>
  <% end %>
<% end %>