Gugubaight Gugubaight - 3 months ago 6
Ruby Question

Rails 4: How to prevent jumping to index




I am fairly new to rails and currently coding my first app.

I created a search for the name of my tools model. It's passing the params correctly but constantly (jumps/redirects/passes the params) to the index of my model. How can I direct it to the tools#search site (site with the search form)?

A URL overview:

http://localhost:3000/search # Start
http://localhost:3000/tools?utf8=%E2%9C%93&search=&commit=Search # Directed to
http://localhost:3000/search?utf8=%E2%9C%93&search=&commit=Search # Where it should direct to


A code overview:

Routes

get '/search' => 'tools#search'


Tool Model

# Search
def self.search(search)
if search
where(["title LIKE ?", "#{search}"])
else
all
end
end


Tools Controller

def search
@tools = Tool.search(params[:search]).order("created_at DESC")
end


Search View (app/views/tools/search.html.haml)

= form_tag search_path, :method => 'post' do
= text_field_tag :search, params[:search]
= submit_tag "Search"

- @tools.each do |tool|
= image_tag tool.cover_filename.url
%h2= link_to tool.title, tool
%p= tool.subtitle
%p= link_to tool.user.try(:username), '/users/'+tool.user_id.to_s
%p= tool.impressionist_count
%p= link_to tool.get_upvotes.size, like_tool_path(tool), method: :get
%p= link_to "Favorite", favorite_tool_path(tool, type: "favorite"), method: :get
%p= link_to "Unfavorite", favorite_tool_path(tool, type: "unfavorite"), method: :get
%p= link_to "Edit", edit_tool_path(tool)
%p= link_to 'http://ocubit.com/tools/'+tool.id.to_s
%p= time_ago_in_words(tool.created_at)


Thanks for all helpful replies, appreciated!

Answer

Change the tools_path to search_path in your view

= form_tag search_path, :method => 'get' do
  = text_field_tag :search, params[:search]
  = submit_tag "Search"

I will also suggest changing the method to POST as its form submission