下拉选择表单,在rails4
Drop-down selection form, in rails 4
我正在尝试创建一个下拉表单,允许从 table 个名称中选择一个名称。
在控制器中我只有:
def selection
@data = Location.all
end
我很难在下拉选择表单中呈现此@data。我尝试过的一切都会产生错误:"undefined method `to_key' for #Location::ActiveRecord_Relation:0x007f07d83b2a90>"
我知道我可能应该使用 "f.collection_select",也许是这样的:
<%= form_for @data do |f| %>
<%= f.collection_select :name, Location.all, :url, :name %>
<% end %>
抱歉,如果这个问题有点愚蠢,我真的是编程新手。如有任何帮助,我们将不胜感激。
谢谢。
而不是 :url
尝试使用 :id
作为主键。
也许这个 link 会对你有所帮助:
http://www.redguava.com.au/2010/12/rails-basics-adding-a-drop-down-list-to-your-forms/
我找到了我需要的东西:
使用我使用的数据填充表单:
@formlist = Location.all.pluck(:name)
我需要的表格代码:
<%= form_for :select, :url => results_path do |f| %>
<%= f.select(:name, options_for_select(@formlist))%>
<%= f.submit %>
<% end %>
results_path 必须是 post 而不是 get:
post 'results' => '<mycontroller>#results'
然后可以使用以下方式选择所选名称:
def results
@choice = (params[:select])[:name]
end
现在能够选择一个@choice 变量让我可以return根据用户输入进行一些分析。
我确信有更好的方法可以做到这一点,但我对自己的想法很满意。
这里的 post“http://www.austinstory.com/rails-select-tag-and-options-for-select-explained/”非常有帮助
我正在尝试创建一个下拉表单,允许从 table 个名称中选择一个名称。
在控制器中我只有:
def selection
@data = Location.all
end
我很难在下拉选择表单中呈现此@data。我尝试过的一切都会产生错误:"undefined method `to_key' for #Location::ActiveRecord_Relation:0x007f07d83b2a90>"
我知道我可能应该使用 "f.collection_select",也许是这样的:
<%= form_for @data do |f| %>
<%= f.collection_select :name, Location.all, :url, :name %>
<% end %>
抱歉,如果这个问题有点愚蠢,我真的是编程新手。如有任何帮助,我们将不胜感激。
谢谢。
而不是 :url
尝试使用 :id
作为主键。
也许这个 link 会对你有所帮助:
http://www.redguava.com.au/2010/12/rails-basics-adding-a-drop-down-list-to-your-forms/
我找到了我需要的东西:
使用我使用的数据填充表单:
@formlist = Location.all.pluck(:name)
我需要的表格代码:
<%= form_for :select, :url => results_path do |f| %>
<%= f.select(:name, options_for_select(@formlist))%>
<%= f.submit %>
<% end %>
results_path 必须是 post 而不是 get:
post 'results' => '<mycontroller>#results'
然后可以使用以下方式选择所选名称:
def results
@choice = (params[:select])[:name]
end
现在能够选择一个@choice 变量让我可以return根据用户输入进行一些分析。
我确信有更好的方法可以做到这一点,但我对自己的想法很满意。
这里的 post“http://www.austinstory.com/rails-select-tag-and-options-for-select-explained/”非常有帮助