# vi app/models/concerns/searchable.rb
module Searchable
extend ActiveSupport::Concern
module ClassMethods
def search(search, attributes: nil)
attributes = self.new.attributes.keys - ["id", "created_at", "updated_at"] if attributes.nil?
like_sql = attributes.map { |attr| "#{attr} LIKE ?" }.join("OR ")
where(like_sql, *(["%#{search}%"]*attributes.size))
end
end
end
# vi app/models/post.rb
class Post < ApplicationRecord
include Searchable
end
# vi app/controllers/posts_controller.rb
def index
if params[:search]
@posts = Post.search(params[:search]).page(params[:page])
else
@posts = Post.page params[:page]
end
end
# vi app/views/posts/index.html.erb
<%= form_tag posts_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>