Rails Blog In VS Code - Ransack v 4
How To Create A Blog in VS Code — Part X — Add Searching To Your Rails App— RailsSeries#Episode 12
Hi! Let’s make a search bar.
In this episode, we will be dealing with Ransack.
Here it is functioning well:
Ransack Gem is amazing for bootstrapping search and sort functionality into an application.
Ransack simplifies the process of implementing search functionality in Rails applications by providing a clean and intuitive interface for constructing search queries and handling search results. It’s widely used in Rails projects to add powerful search capabilities with minimal effort.
Welcome aboard!
In this post (based on Deanin):
You will:
Learn How to Use Ransack version 4.1;
Let’s Get Started!
Note: if you get stuck, please see my repo.
To integrate Ransack into your Rails 7 website, you can follow these general steps:
0#step — Download the last version (v8) post here and prepare your vscode
environment.
Let’s open a new Feature Branch: git checkout -b add_ransack
.
1#Step — Install the Ransack Gem: Add the Ransack gem to your Gemfile:
bundle add ransack -v 4.1
2#Step — Then, run bundle install
to install the gem.
bundle install
3#Step — GoTo Post
model, add the following line to:
app/models/post.rb
...
def self.ransackable_attributes(_auth_object = nil)
%w[title body created_at updated_at user_id]
end
def self.ransackable_associations(_auth_object = nil)
%w[posts users comments notifications action_text_rich_texts]
end
...
In Ransack 4, the ransackable_attributes
and ransackable_associations
methods are used to specify which attributes and associations of a model can be searched and filtered using Ransack's search form.
ransackable_attributes
: This method defines which attributes of the model can be searched and filtered through Ransack’s search form; In the provided example,%w[title body created_at updated_at user_id]
indicates that thetitle
,body
,created_at
,updated_at
, anduser_id
attributes are searchable; The_auth_object
parameter is not used in this example. It's typically used for authorization purposes to control which attributes are accessible based on the current user's permissions.ransackable_associations
: This method specifies which associations of the model can be searched and filtered using Ransack’s search form; the provided example%w[posts users comments notifications action_text_rich_texts]
indicates that theposts
,users
,comments
,notifications
, andaction_text_rich_texts
associations are searchable; Likeransackable_attributes
, the_auth_object
parameter is not used in this example.
These methods are used to customize the behavior of Ransack’s search form by specifying which attributes and associations can be searched. By default, Ransack will attempt to search all attributes and associations of a model unless these methods are explicitly defined to restrict or customize the search behavior.
4#Step — Navigate to Terminal and execute for controller:
rails g controller search index
5#Step — GoTo and include this route:
config/routes.rb
get 'search', to: 'search#index'
6#Step — Update Views with Search Form: Add a search form to your views where you want to include search functionality. For example, you can create a form using the search_form_for
helper. For now, let’s create a partial to render within the index.html.erb
file, placed above other content. This partial will encapsulate specific elements or sections of our page for better organization and maintainability:
app/views/search/_form.html.erb
<li class="nav-item dropdown">
<%= search_form_for @query, url: search_path, method: :get, html: { class: "d-flex", role: "search" } do |f| %>
<%= f.search_field :title_or_body_cont, class: "form-control me-2" , placeholder: "Search..."%>
<%= f.submit "Search", class: "btn btn-outline-secondary-light btn-sm" %>
<% end %>
</li>
7#Step — Handle Search in Controller: In your controller, use Ransack to perform the search based on the parameters received from the form:
app/controllers/search_controller.rb
class SearchController < ApplicationController
# # see app/controllers/application_controller.rb
def index
@query = Post.ransack(params[:q])
@posts = @query.result(distinct: true)
end
end
8#Step — GoTo and type:
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
...
before_action :set_query
def set_query
@query = Post.ransack(params[:query])
@posts = @query.result(distinct: true)
end
...
end
9#Step — Display Search Results: Finally, display the search results in your views as per your application's requirements:
app/views/search/index.html.erb
<h1 class= "text-center"> <%=pluralize(@posts.count, "Result") %> </h1>
<%# See the app/views/layouts/_navbar.html.erb %>
<%#= render 'search/form' %>
<div class= "container">
<table class="table table-light table-striped">
<thead>
<tr>
<th><%= sort_link(@query, :title, "Title", default_order: :asc) %></th>
<th><%= sort_link(@query, :body, "Blog Content") %></th>
<th><%= sort_link(@query, :user.name, "users") %>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @posts.each do |post| %>
<tr>
<td><%= link_to post.title, post %></td>
<td><%= post.body.truncate_words(5) %></td>
<td><%= link_to post.user.name, post.user %></td>
<th colspan="3"></th>
</tr>
<% end %>
</tbody>
</table>
<br>
</div>
10#Step — Navigate to the navbar file and include the rendering of the search form within it (see 07#step):
app/views/layouts/_navbar.html.erb
....
<ul class="navbar-nav">
<%= render 'search/form' %>
... above this lie....
<%= render 'layouts/notifications' %>
</ul>
...
11#Step — Testing and upload to your GitHub Repo: Test the search functionality thoroughly to ensure it works as expected.
Following these steps should help you integrate Ransack into your Rails 7 website, allowing users to search your content easily. Make sure to refer to the Ransack documentation for more advanced configurations and options as needed.
That’s all folks!
See you in the next episode [TODO: LINK TO THE NEXT POST]👋️👋️👋️!
Git Commands:
....
rails db:drop
rails db:migrate
rails s
git status
git remote -v
git pull
git add -A
git commit -m ":lipstick: Ransack 4.1: Implemets and Integrates"
git push --set-upstream origin add_ransack
remote: Create a pull request for 'add_ransack' on GitHub by visiting:
remote: https://github.com/giljr/rails_blog_demo/pull/new/add_ransack
[GoTo your GIT REPO and Merge the Request]
[Returns to vscode]
git checkout master
git status
git fetch
git merge add_ransack
git pull
history > history.txt
Credits & References
Adding A Search Bar To Your Blog | Ruby On Rails For Beginners Part 6 by Deanin
Ransack Code by github.com
For v2 let’s Tag it all!
git tag -a rails_blog_v10 -m "Blog in Rails 7- v10: Go to https://medium.com/jungletronics/a-rails-blog-in-vs-code-quick-start-5c3173191a64" -m "0- Learn How to Use Ransack version 4.1;" -m "1- Generate Ransack Configuration;" -m "2- Modify Post model;" -m "3- Create 'ransackable_attributes' and 'ransackable_associations' methods;" -m "4- Create route, forms to search in the navbar, and views to display" -m "5- Create search controller and modify application controller;" -m "Thank you for downloading this project 😍️"
git push origin rails_blog_v10
Search Matchers
Related Posts:
00# Episode — RailsSeries — Installing Ruby on Rails Using ASDF — Why ASDF is Better Than RBENV for Rails Bootstrap App?
01# Episode — RailsSeries — How To Send Email In Rails 7? — User Registration and Onboarding.
02# Episode — RailsSeries — 14 Ruby Extensions 4 Vs Code — Based On This Deanin’s video.
03# Episode — RailsSeries — A Rails Blog In VS Code — Quick Start — How To Create A Blog in VS Code — Part I
04# Episode — RailsSeries — A Rails Blog In VS Code — Styling — How To Create A Blog in VS Code — Part II
05# Episode — RailsSeries — A Rails Blog In VS Code — Create Posts — How To Create A Blog in VS Code — Part III
06# Episode — RailsSeries — A Rails Blog In VS Code — Posts Tips&Tricks — How To Create A Blog in VS Code — Part IV
07# Episode — RailsSeries — A Rails Blog In VS Code — Devise — How To Create A Blog in VS Code — Part V
08# Episode — RailsSeries — A Rails Blog In VS Code — Add Comments to Post — How To Create A Blog in VS Code — Part VI
09# Episode — RailsSeries — Rails Blog In VS Code — Using Stimulus — How To Create A Blog in VS Code — Part VII
10# Episode — RailsSeries — Rails Blog In VS Code — Noticed V1 — Notifications for your Ruby on Rails app — Part VIII
11# Episode — RailsSeries — Rails Blog In VS Code — Noticed V2 — Notifications for your Ruby on Rails app — Part IX
12# Episode — RailsSeries — Rails Blog In VS Code —Ransack 4 — Add Searching To Your Rails App — Part X (this one)