0

I want to create a search box (form) that when submitted will pass the search_word into the query string.

<%= link_to articles_path(title: "search_word") %>

class Article < Active Record::Base
  scope :title, -> (title) { where("title ILIKE ?", "%#{title}%")}
end

class ArticlesController < ApplicationController
  def index 
    @articles = Article.all
    @articles = @articles.title(params[:title]) if params[:title].present? 
  end
end

This will allow the User to use the search box to search the articles by title.

Timmy Von Heiss
  • 2,160
  • 17
  • 39

1 Answers1

3

The idea here is that you must provide a form for the user to enter data and submit it to your app.

In your view, change this:

<%= link_to articles_path(title: "search_word") %>

into this form:

<%= form_tag articles_path, method: :get do %>
  <%= text_field_tag "title", params[:title], placeholder: "Search by title" %>
  <%= submit_tag "Search" %>
<% end %>

The form_tag is passed the path of the controller#action that will handle the search. Then a text field is created to allow the user to type in a search term - this value will be available in your controller via params[:title]. We give the text field params[:title] as a second argument so that it will display any previous search term the user may have typed in. The placeholder: let's the user know what attribute the articles will be searched by. Finally, a submit_tag is created to allow the user to submit the form.

P.S Note form is of GET type so whatever the value user typed in will be available as query params in url. So if you wanna bookmark search results then it can be possible.

DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55
  • this works however the following is being shown as the placeholder.... {:value=>nil, :placeholder=>"Search by title"} ...not "Search by title"... – Timmy Von Heiss Jun 29 '16 at 17:51
  • Oops, I got my APIs mixed up, remove the 'value:' part so that the second argument is just 'params[:title]' – DiegoSalazar Jun 29 '16 at 18:17
  • please see this topic - http://stackoverflow.com/questions/38130833/using-will-paginate-while-applying-a-scope-with-params-to-the-model - a similar question to this topic. – Timmy Von Heiss Jun 30 '16 at 18:37