🐈

ActiveRecordのorについて

2023/09/14に公開

概要

ActiveRecordのorについて挙動を確認しました。

A.or(B)の場合

Book.where(title: '夜行').or(Book.where(title: 'ホワイトラビット'))

以下は、発行されるSQLクエリになります。

Book.
where
    (title : '夜行').
or  (Book.where(title : 'ホワイトラビット'))

複数条件のA.or(B)の場合

Book.where(title: '夜行', author: '森見登美彦').or(Book.where(title: 'ホワイトラビット'))

以下は、発行されるSQLクエリになります。

SELECT
    "books".*
FROM
    "books"
WHERE
    (
        "books"."title" = '夜行'
    AND "books"."author" = '森見登美彦'
    OR  "books"."title" = 'ホワイトラビット'
    )

A.or(B).or(C)の場合

Book.where(title: '夜行').or(Book.where(title: 'ホワイトラビット')).or(Book.where(title: 'らせん階段'))

以下は、発行されるSQLクエリになります。

SELECT
    "books".*
FROM
    "books"
WHERE
    (
        "books"."title" = '夜行'
    OR  "books"."title" = 'ホワイトラビット'
    OR  "books"."title" = 'らせん階段'
    )

A.or(B.or(C))の場合

Book.where(title: '夜行').or(Book.where(title: 'ホワイトラビット').or(Book.where(title: 'らせん階段')))

以下は、発行されるSQLクエリになります。

SELECT
    "books".*
FROM
    "books"
WHERE
    (
        "books"."title" = '夜行'
    OR  "books"."title" = 'ホワイトラビット'
    OR  "books"."title" = 'らせん階段'
    )

Discussion