Robert Robert - 5 months ago 13
Ruby Question

Rails search form with no path

I would like my search form to work on all URLs instead of redirecting to the messages page. For example on the search for "hi":

on /messages return /messages?utf8=✓&search=hi&commit=Search

on /posts return /posts?utf8=✓&search=hi&commit=Search


In my application view (bootstrap styling):

<%= form_tag(messages_path, :method => "get", class: "navbar-form navbar-left") do %>
<div class="form-group">
<%= text_field_tag :search, params[:search], placeholder: "Search", class: "form-control" %>
</div>
<%= submit_tag "Search", class: "btn btn-default" %>
<% end %>


Messages controller:

def index
if params[:search]
@messages = Message.search(params[:search]).order("created_at DESC")
else
@messages = Message.all.order("created_at DESC")
end
end


Users controller:

def index
if params[:search]
@users = User.search(params[:search]).order("created_at DESC")
else
@users = User.all.order("created_at DESC")
end
end


Message model:

def self.search(search)
where("title LIKE ?", "%#{search}%")
end


User model:

def self.search(search)
where("username LIKE ?", "%#{search}%")
end


If I copy and paste the parameters
(?utf8=✓&search=hi&commit=Search)
onto the pages, they work fine. I tried removing
messages_path
from the form, but I got an error. How do I use a form path that changes based on which controller I'm using it from?

Answer

You should be able to replace messages_path with url_for that includes the controller/action hash:

<%= form_tag(url_for(controller: controller_name, action: "search"), :method => "get", class: "navbar-form navbar-left") do %>

This will give you the /#{controller_name}/search path based on whichever controller is serving the form view.

If you want the search to go to the index, simply use this variation:

<%= form_tag(url_for(controller: controller_name, action: "index"), :method => "get", class: "navbar-form navbar-left") do %>

and it will send the form to /#{controller_name}, instead.