Rails选择选项标记 - 从关联生成选项

时间:2013-08-26 22:32:29

标签: ruby-on-rails erb html-select

我有一个视图,允许用户将list_items添加到其中一个shopping_lists。我希望select的选项是其列表的名称,但我需要将这些名称映射到相应的list_id以获得正确的关联。这是我目前的select tag

<tr>
  <% item.inventory_items.each do |product| %>
    <td>
      <%= form_tag("/list_items", method: "post") do %>
      <%= hidden_field_tag(:item_id, item.id) %>
      <%= hidden_field_tag(:inventory_item_id, product.id) %> 
      <%= select_tag(:shopping_list_id, options_for_select(current_user.shopping_lists)) %>
      <%= submit_tag("$#{product.price}", class: "btn btn-primary") %>
      <% end %>
    </td>
  <% end %>
</tr>

如何显示用户shopping_lists的名称作为选项,但是返回相对shopping_list_id作为该选项的值?

ShoppingList belongs_to :user 用户has_many :shopping_lists

目前,我的选择标记会显示用户购物清单的下拉列表选项,但选项列在表单中,“#。单击提交按钮实际上不会将该项目添加到列表中。

提前致谢!

1 个答案:

答案 0 :(得分:3)

正如您在Rails Api文档中看到的那样:

options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
# => <option value="$">Dollar</option>
# => <option value="DKK">Kroner</option>

options_for_select收到一个数组数组。内部数组只有两个元素:["name", "value"]

您可以在ShoppingList模型中创建一个类方法,如下所示:

def self.options_for_list(shopping_lists)
  shopping_lists.map do |sl|
    [ sl.name, sl.id ]
  end
end

它返回您需要的数组,然后:

<%= select_tag :shopping_list_id, options_for_select(ShoppingList.options_for_list(current_user.shopping_lists)) %>

修改

或者使用辅助方法:

def shopping_list_select_tag(shopping_lists, options = {})
  select_options = shopping_lists.map do |sl|
                     [ sl.name, sl.id ]
                   end
  select_tag :shopping_list_id, options_for_select(select_options), options
end

然后,

<%= shopping_list_select_tag current_user.shopping_lists %>