无法通过rails中的集合选择传递变量

时间:2015-09-06 20:40:14

标签: ruby-on-rails

我正在尝试使用集合选择并从那里转到我的user_show页面,但我似乎无法弄清楚如何发送所选变量以进行显示。

这是我目前的代码:

<%= form_tag user_path(:id), :method => :post do %>
  <%= collection_select(:user, :id, User.all, :id, :name) %>
  <button type="submit">Sign In</button>
<% end %>

这是我得到的最接近的,但它正在读取:id为id。这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

你的collection_select应该是这样的(每个字段的解释):

collection_select(
    :user, # field namespace
    :user_id, # field name
    # result of these two params will be: <select name="user[user_id]">

    # then you should specify some collection or array of rows.
    # In your example it is:
    User.all,

    # then you should specify methods for generating options
    :id, # this is name of method that will be called for every row, result will be set as key
    :name, # this is name of method that will be called for every row, result will be set as value

# as a result, every option will be generated by the following rule:
# 'user' is an element in the collection or array
)

所以,将collection_select更改为:

<%= collection_select(:user, :user_id, User.all, :id, :name) %>

答案 1 :(得分:1)

您可能需要:

<%= form_tag user_path(:id), :method => :post do %>
  <%= collection_select(:user, :user_id, User.all, :id, :name) %>
  <button type="submit">Sign In</button>
<% end %>