ActiveRecord关联Scope报错:列'id'引用歧义问题
解决PostgreSQL字段歧义与查询逻辑问题
错误原因
你遇到的PG::AmbiguousColumn错误,是因为users和user_profiles表都包含id字段,执行JOIN查询时,PostgreSQL无法确定id > 20000里的id属于哪个表,导致字段引用歧义。
同时原查询逻辑存在偏差:两个where.not(user_profile: {xxx: ''})是要求两个字段同时不为空,但你实际需求是description或website任意一个填写就判定为机器人,需要改成逻辑OR关系。
修正后的代码
class User < ApplicationRecord has_one :user_profile, dependent: :destroy scope :possible_bots, -> { joins(:user_profile) # 明确指定users表的id,解决字段歧义 .where("users.id > ?", 20000) # 用OR逻辑匹配description或website不为空的情况 .where("user_profiles.description != '' OR user_profiles.website != ''") } end
更优雅的ActiveRecord写法
如果偏好不用原生SQL字符串,也可以这样写:
class User < ApplicationRecord has_one :user_profile, dependent: :destroy scope :possible_bots, -> { joins(:user_profile) .where(users: { id: 20001.. }) .where(user_profile: { description: !'' }).or(where(user_profile: { website: !'' })) } end
这样既解决了字段歧义的报错,又完全符合你设定的机器人账号判定逻辑。
内容的提问来源于stack exchange,提问作者Roberto Pezzali
相关产品推荐
相关产品推荐

