2

我有一个视图,允许用户添加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值作为该选项的值?

购物清单belongs_to :user 用户has_many :shopping_lists

目前我的选择标签呈现用户购物清单的下拉选择,但选项以'#. 单击提交按钮实际上也不会将该项目添加到列表中。

提前致谢!

4

1 回答 1

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 %>
于 2013-08-26T23:35:53.543 回答