how to get value selected by using select_tag with options_from_collection_for_select and pass it to controller

Thanh picture Thanh · Nov 2, 2012 · Viewed 13.5k times · Source

I have built a form search like this:

<%= form_tag({ controller: 'questions', action: 'search_topic' }, method: 'get') do %>
  <%= select_tag 'search_topic', options_from_collection_for_select(current_user.get_topics, :id, :name) %>
  <%= submit_tag "Search", name: nil, class: 'btn' %>
<% end %> 

I want to search all questions of a topic selected from select box, i used sunspot to help for search, so now how can i pass value select from select box to controller for search, i used below code to pass a params[:search]:

<%= select_tag 'search_topic', options_from_collection_for_select(current_user.get_topics, :id, :name), params[:search] %>

but it has error:

undefined method `[]' for nil:NilClass

this is my controller:

def search_topic
  @search = Question.search do
    with(:topic_id, params[:search])
    paginate page: 1, per_page: 10
  end

  @questions = @search.results
  render 'index'
end

so, how can i pass value selected from select box on form to controller for search?

Answer

RadBrad picture RadBrad · Nov 2, 2012
<%= select_tag 'search_topic', 
  options_from_collection_for_select(current_user.get_topics, :id, :name) %>

This assumes the view code shown is inside a form. If that form posts, it ends up say in the create action with:

params[:search_topic]

containing the value you selected.