LoginSignup
1
1

More than 5 years have passed since last update.

検索条件を指定してdbから取得

Posted at

条件を指定してdbから取得するメソッド集

where(条件)

使い方

  モデル.where(条件)

例:

文字列で指定

Page.where("category_id = '1'")
# SELECT "pages".* FROM "pages" WHERE "pages"."category_id" = 1

ハッシュで指定

Page.where(category_id: 1)
# SELECT "pages".* FROM "pages" WHERE "pages"."category_id" = 1

配列で指定

Page.where(["category_id = ? and url_id = ?", 1, 1])
# SELECT "pages".* FROM "pages" WHERE (category_id = 1 and url_id = 1)

nilのすべてのデータを取得

Page.where("title = ?", nil)
# SELECT "pages".* FROM "pages" WHERE (title = NULL)

nilでないすべてのデータを取得

Page.where("title not ?", nil)
# SELECT "pages".* FROM "pages" WHERE (title not NULL)
1
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
1
1