WebDev Rails
No gems, no dependencies, no complexity. Here’s a basic full text search to use on simpler, smaller rails apps.
before_action :set_scope, only: :index
def set_scope
@posts = Post.all
if params[:search]
basics = search_basics
body = search_body
tags = search_tags
post_ids = basics | body | tags
@posts = @posts.find(post_ids)
end
end
def search_basics
@posts.where(
"title ilike ? OR description ilike ?",
"%#{params[:search]}%","%#{params[:search]}%"
).pluck(:id)
end
def search_body
@posts.joins(:action_text_rich_text)
.where(
"action_text_rich_texts.body ilike ?",
"%#{params[:search]}%"
).pluck(:id)
end
def search_tags
tags = params[:search].split(" ")
Post.tagged_with(tags, :any => true).pluck(:id)
end
<form id="search" action="<%= posts_path %>">
<div class="input-group">
<%= text_field_tag :search, params[:search], id: 'content_search_term',class: 'form-control', placeholder:'Search...' %>
<div class="input-group-append">
<button class="btn btn-primary" type="submit" id="button-addon2">Search</button>
</div>
</div>
<% unless params[:search].blank? %>
<small><%= pluralize(@posts.count, "post", "posts") %> found for search "<%= params[:search] %>" <a href="<%= posts_path %>" class="text-muted pl-2 text-decoration-none"><i class="fas fa-times"></i> Clear Search</a></small>
<% end %>
</form>
Similar Posts