Skip to content

Instantly share code, notes, and snippets.

@EastResident
Last active January 16, 2018 08:57
Show Gist options
  • Save EastResident/efedd2cd846db8267473fb4eafa8aaf0 to your computer and use it in GitHub Desktop.
Save EastResident/efedd2cd846db8267473fb4eafa8aaf0 to your computer and use it in GitHub Desktop.
検索用Gem"SearchCop"の紹介 ref: https://qiita.com/EastResident/items/092495a4eff8406bd492
# 性・名・電話番号でのAND検索
User.search('田中 太郎 08012345678')
# メールアドレスに"gmail"が含まれており、登録が2015年あるいは2016年
User.search('email: gmail AND (created_at:2015 OR created_at:2016)')
class User < ApplicationRecord
has_many :posts
end
class Post < ApplicationRecord
belongs_to :user
end
class User < ApplicationRecord
include SearchCop
has_many :posts
search_scope :search do
attributes :email, :first_name, :last_name, :age, :created_at
attributes post: ['posts.title', 'posts.message']
end
end
User.search('Ruby')
search_scope :name_search do
attributes :first_name, :last_name, created_at
end
search_scope :post_search do
attributes post: ['posts.title', 'posts.message']
end
# last_nameのみを検索
User.search('last_name:松本')
# 2017年に登録されたもののみ
User.search('created_at:2017')
# ageが20より上
User.search('age > 20')
User.search('(last_name:松本 OR age > 20) AND created_at:2017')
search_scope :search do
attributes message: 'posts.message'
options :message, type: :fulltext
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment