railsでscopeを追加していたら上記のエラーが発生しました

やりたいこと

parentの中身を検索したいのですが、なぜか入らず調べてみたら、joinsした後のテーブルの指定方法が悪かったみたいです

class User 
  has_many :children
end

class Child
  belongs_to :user
  # parentの中身をscopeで検索したい
end

解決策

joinsではrelation name を指定し、where句の中ではtable name を指定すべきらしいです。

#joins uses the relation name, but #where uses the table name. I can’t tell what’s the standard anymore. I’d say there’s no issue then.
scope :without_x_user, -> {
  joins(:user).where.not(users: { # 何かしら条件書く })
}

参考記事

Search in association throws missing FROM-clause entry #92

コメントをどうぞ

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA