2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】gemなしで検索機能を実装する

Posted at

実装環境

Rails 5.1.7
Ruby 2.4.0
Slimで実装

#やりたいこと
実装済のuserを検索したい
検索条件はあとから追加できるようにしたい
今回は名前検索を行う

参考記事

https://freesworder.net/rails-search/
https://www.sejuku.net/blog/71189
※ 個人的にわからないところがいっぱいだったので調べながら

models/user.rb
class User < ActiveRecord::Base
  def self.search(search)
    if search
      User.where(['name LIKE ?', "%#{search}%"])
    else
      User.all
    end
  end
end
検索フォーム
= form_tag users_path, method => 'get' do
  p
    = text_field_tag :search, params[:search]
    = submit_tag "Search", :name => nil
controllers/users_controller.rb
class UsersController < ApplicationController
  def index
    @users = User.search(params[:search]
  end
end

補足: LIKEによるあいまい検索

SQLにはLIKE句を使ったあいまい検索の構文がある
~ WHERE 列名 LIKE '%検索値%'
~ WHERE 列名 LIKE '検索値_'

% → 0文字以上の任意の文字列
_ → 任意の1文字

ModelClass.where("列名 LIKE ?", "%値%") # 値(文字列)を含む
ModelClass.where("列名 LIKE ?", "値_" # 値(文字列)と末尾の一文字




2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?