1
0

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 5 years have passed since last update.

Rails Ruby 検索の仕方

Last updated at Posted at 2019-05-14

Rails Ruby 検索の仕方

基本的なところで理解しきれてなかったので、まとめておく。Userモデルデータは次の通り

id:8 name:山田太郎 department:開発部 email: yamada@gmail.com まずはターミナルから該当のフォルダに入り
>#rails c

id(インデックスで検索する)

>User.find(8)
>SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 8], ["LIMIT", 1]]
> => #<User id: 8, name: "山田太郎", email: "yamada@gmail.com", created_at: "2019-05-13 21:29:13", updated_at: "2019-05-13 21:29:13,department: "開発部

以下検索結果は同じで省略
名前で検索

>User.find_by(name:"山田太郎")

whereで名前検索

>User.where(name:"山田太郎")

複数検索

>User.where(name: '山田太郎', department:"開発部")

曖昧検索
where("カラム名 like '%検索テキスト%'")

>User.where("name like '%山田%'")

orあるいは
データ
id:4
name:伊藤五郎
department:業務部
email: itogoro@gmail.com

>User.where(name: '山田太郎').or(User.where(department:"業務部"))
結果
User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE ("users"."name" = ? OR "users"."department" = ?) LIMIT ?  [["name", "山田太郎"], ["department", "業務部"], ["LIMIT", 11]]
 =># #<ActiveRecord::Relation [#<User id: 4, name: "伊藤五郎", email: "itogoro@gmail.com", created_at: "2019-05-12 04:36:29", updated_at: "2019-05-13 21:56:54",  department: "業務部">, #<User id: 8, name: "山田太郎", email: "yamada@gmail.com", created_at: "2019-05-13 21:29:13", updated_at: "2019-05-13 21:29:13,department: "開発部"

参考にしたサイト
https://qiita.com/QUANON/items/0033a5adb76d0cb963cd
以上間違ってたらご指摘下さい

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?