
This is a tutorial on setting up a search field/form in your rails app. This tutorial assumes that you already have a rails app with a post and category model (associated together). To get to this point, you'll find a link below to help you with getting to this point. Let's get started =>
In gemfile =>
gem 'ransack'
In application_controller.rb =>
before_action :site_search
def site_search
@q = Post.ransack(params[:q])
@q_posts = @q.result.order("created_at DESC").includes(:category)
end
In posts_controller.rb =>
def index
@q = Post.ransack(params[:q])
@posts = @q.result.order("created_at DESC").includes(:category)
end
In Layouts/application.html.erb (or posts index.html.erb) =>
<%= search_form_for @q do |f| %>
<%= f.search_field :title_or_body_or_category_title_cont, class: 'form-control', placeholder: 'Search' %>
<%= f.submit 'search', class: 'btn btn-default' %>
<% end %>
Link to: Rails Post app with Category association Photo by: Kyle Popineau
About ohiodn8
Ruby on Rails developer, AWS Engineer, anything fun, music, a little bit of mobile game. . .