To implement search functionality in Ruby on Rails, you can follow these steps:
1. Add a search form to your view:
– In your view file (e.g., `index.html.erb`), add a form that allows users to enter their search query. For example:
“`ruby
<%= form_tag search_path, method: :get do %>
<%= text_field_tag :query, params[:query], placeholder: "Search…" %>
<%= submit_tag "Search" %>
<% end %>
“`
2. Create a search action in your controller:
– In your controller file (e.g., `posts_controller.rb`), add a new action called `search` that handles the search functionality. For example:
“`ruby
def search
@query = params[:query]
@results = Post.where("title LIKE ?", "%#{@query}%")
end
“`
3. Create a search route in your routes file:
– In your `routes.rb` file, add a new route that maps to the search action in your controller. For example:
“`ruby
get ‘/search’, to: ‘posts#search’, as: ‘search’
“`
4. Display search results in your view:
– In your view file (e.g., `search.html.erb`), iterate over the `@results` variable and display the search results. For example:
“`ruby
<% @results.each do |result| %>
<%= result.title %>
<%= result.content %>
<% end %>
“`
5. Handle empty search queries:
– To handle empty search queries, you can add a condition in your controller to check if the `@query` variable is present. For example:
“`ruby
def search
@query = params[:query]
if @query.present?
@results = Post.where("title LIKE ?", "%#{@query}%")
else
@results = []
end
end
“`
That’s it! You have now implemented search functionality in your Ruby on Rails application.