Rails 5 ActiveRecord クエリ
概要
モデルユーザーと記事。
Article モデルのリレーションシップでは、belongs_to:user が定義されています。ユーザーモデルのリレーションシップで has_many :articles が定義されています
以下のクエリをトリガーすると、成功した結果が得られます
Article.select(:name, :id).where(user_id:"fb157fc-a9353453cb95", name:"first")
しかし、以下のクエリをトリガーすると、エラーが発生します
Article.select(:name, :id).where("user_id (?)","1bf4c2fc-35c37e15d4b5")
エラー ActiveRecord::StatementInvalid ヒント: 指定された名前と引数の型に一致する関数はありません。明示的な型キャストの追加が必要になる場合があります。
ただし、以下のクエリをトリガーすると、エラーも発生します
Article.select(:name, :id).where("articles.user_id (?)","1bf4c2fc-35c37e15d4b5")
エラー ActiveRecord::StatementInvalid
解決策
おそらくINクエリを探していると思います その構文は次のとおりです: -
user_ids = [1bf4c2fc-35c37e15d4b5,2nd_user_id, 3rd_user_id]
Article.select(:name, :id).where("user_id IN (?)",user_ids)
このようなSQLクエリを作成します
SELECT "articles"."name","articles"."id" FROM "articles" WHERE (user_id IN (1bf4c2fc-35c37e15d4b5,2nd_user_id, 3rd_user_id))
where ブロックで 1 つの user_id に対するクエリを探している場合、その構文は次のようになります。
user_id = 1bf4c2fc-35c37e15d4b5
Article.select(:name, :id).where("user_id = ?",user_id)
次のようなSQLクエリを作成します: -
SELECT "articles"."name","articles"."id" FROM "articles" WHERE (user_id =
"1bf4c2fc-35c37e15d4b5")
上記の 2 つのクエリにより、複数の user_id を検索する IN と 1 つの user_id を検索する IN の違いが明確になることを願っています。