LoginSignup
5
3

More than 3 years have passed since last update.

【Rails】PG::AmbiguousColumn: ERROR: column reference "name" is ambiguous

Posted at

【Rails】PG::AmbiguousColumn: ERROR: column reference "name" is ambiguous

アソシエーションが張られた同じカラム名を持つ2つのモデルでそのカラム名を使ったメソッドを定義したところ上記のエラーが出ました。その際の対応内容をまとめます。

目次


動作環境

OS : macOS 10.14.6
ruby : 2.6.5
Rails : 5.2.4.2

状況

カテゴリモデルユーザモデルはそれぞれnameという同じ名前のカラム名を持ち,多対多のアソシエーションが張られている状況です。

image.png

ここでユーザモデルカテゴリモデル

それぞれにモデルのスコープメソッドを定義しています。

category.rb
class Category < ApplicationRecord
  has_many :category_users, dependent: :destroy
  has_many :users, through: :category_users, source: :user

  #検索画面で選択したキーワード名から該当のキーワードを取得するメソッド
  scope :select_category, ->(category) { where('name = ?', category) }
end
user.rb
class User < ApplicationRecord
  has_many :category_users, dependent: :destroy
  has_many :categories, through: :category_users, source: :category

  #カテゴリモデルのスコープ`select_category'を呼び出している
  scope :category_users, ->(category) { joins(:categories).merge(Category.select_category(category)) }
end

この状態でキーワードを選択して実行すると
image.png

image.png

PG::AmbiguousColumn: ERROR: column reference "name" is ambiguousというエラーが出ます.

解決策

上記のエラーはnameカラムが曖昧だというエラーです。
そこでカテゴリモデルのスコープメソッドにテーブル名を付けます。

category.rb
class Category < ApplicationRecord
  has_many :category_users, dependent: :destroy
  has_many :users, through: :category_users, source: :user

  # name -> categories.nameとすることでカテゴリテーブルのnameカラムと明示する
  scope :select_category, ->(category) { where('categories.name = ?', category) }
end

無事、検索ができました。
image.png

原因

下記のSQLログの末尾を見るとWhere name = 'abcc..'にテーブル名が付いていないことがわかる.

: SELECT  "users".* FROM "users" INNER JOIN "category_users" ON "category_users"."user_id" = "users"."id" INNER JOIN "categories" ON "categories"."id" = "category_users"."category_id" WHERE name = 'abccccdd' 

つまり,UserモデルからCategoryモデルのスコープメソッドを呼び出した際に,ActiveRecordではどちらのテーブルのnameか判別することができないためエラーが発生したと考える

5
3
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
5
3