我有一张表格:
<%= form_tag("index", method: "get") do %>
<%= label_tag(:query, "Search for:") %>
<%= text_field_tag(:query) %>
<select>
<%= options_for_select Species.all.collect{|sp| [sp.name, sp.id]}.insert(0, "Select Species") %>
</select>
<%= submit_tag("Search") %>
<% end %>
我可以通过:query
访问控制器中的params[:query]
。我希望能够在提交表单时使用options_select_for
的下拉菜单执行相同的操作,即访问params[:species]
。
我尝试过这样的事情:
<%= :species, options_for_select Species.all.collect{|sp| [sp.name, sp.id]}.insert(0, "Select Species") %>
但Rails似乎不喜欢这样做并返回错误,因此我认为这不是正确的语法。如何在表单中访问多个参数值?
这是错误:
Started GET "/proteins/index" for ::1 at 2015-08-21 12:11:52 -0700
Processing by ProteinsController#index as HTML
[]
Rendered proteins/index.erb within layouts/application (2.0ms)
Completed 500 Internal Server Error in 11ms (ActiveRecord: 0.0ms)
SyntaxError (C:/Users/Shams/Documents/Overall/topfind4/topfind4.1/app/views/proteins/index.erb:18: syntax error, unexpected ',', expecting ')'
...utput_buffer.append=( :species, options_for_select Species.a...
... ^):
app/views/proteins/index.erb:18: syntax error, unexpected ',', expecting ')'
我使用的是Rails 4.2和Ruby 2.0.0。
答案 0 :(得分:4)
删除您自己的<select>
标记,然后尝试使用这样的rails方式
<%= select_tag :species, options_for_select(Species.all.collect{|sp| [sp.name, sp.id]}, params[:species]), {prompt: "Select Species"} %>
也许就像上面提到的评论一样。在controller action
这样的
@species_names = Species.pluck(:name, :id) #as per suggestion give in comment below
OR
@species_names = Species.all.collect{|sp| [sp.name, sp.id]}
并在视图中使用它
<%= select_tag :species, options_for_select(@species_names, params[:species]), {prompt: "Select Species"} %>
这将是更好的方法。