d_a_n
d_a_n

Reputation: 317

Rails search form submit to show method

I am trying to set up a form in a Rails view to submit an id back to the show method in the controller. My form uses autocomplete to set the hidden id field:

<%= form_tag students_path, id: 'search_student_name', method: :get do %>
  <%= text_field_tag :search_name, '', size: 30 %>
  <%= hidden_field_tag :id %>
  <%= submit_tag "Search", name: nil %>
<% end %>

I'm using the standard controller 'show' method generated by the scaffold:

# GET /students/1
# GET /students/1.json
def show
  @student = student_scope.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @student }
  end
end

I'd be grateful for any advice on the combination of form url / post method / additional routes to get this to work. Is this the way you'd normally do this is Rails, or should I set up a new controller method to handle the submitted form?

Thanks in advance

Upvotes: 3

Views: 5036

Answers (1)

Chris Aitchison
Chris Aitchison

Reputation: 4654

Because it is not exactly a Restful show, you should create a new action, search.

#routes.rb
post 'search' => 'students#search'

#student_controller.rb
def search
   @student = Student.find_by_name params[:search_name]
   render action: 'show'
end

The form doesn't need to send the :id as far as I can tell.

<%= form_tag search_path, method: :get do %>
  <%= input_tag :search_name, type: 'text' %>
  <%= submit_tag "Search" %>
<% end %>

Upvotes: 3

Related Questions