Thanh
Thanh

Reputation: 8604

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

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?

Upvotes: 4

Views: 14526

Answers (2)

RadBrad
RadBrad

Reputation: 7304

<%= 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.

Upvotes: 4

Akshay Vishnoi
Akshay Vishnoi

Reputation: 1262

Hey there is no need to pass params[:search].
Rails automatically generates params for select when submit button would be clicked.

If you want to params name to be 'search', then change the name of select 'search-topic' to 'search'.

If you want to check value of params, that how would it recieve in params, try debugger and check value of params generated by this form.

Also, there is a shortcut, try to put an error in the action to be called after pressing submit, and read params on the browser page. Also you can print in flash on next page

Upvotes: 3

Related Questions