条件を指定して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)
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.