Ruby on rails 如何为属于其他两个模型并排除具有匹配外键的所有记录的模型编写作用域

Ruby on rails 如何为属于其他两个模型并排除具有匹配外键的所有记录的模型编写作用域,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我想为一个属于另外两个模型的模型编写一个作用域。此范围应选择一个模型的值不等于其父模型值的所有记录。我下面所说的似乎应该有用: Class Blob belongs_to :user belongs_to :item scope: :not_owned_by_item_owner, -> { where.not(user_id: item.owner.id) } end 但是,在控制器中的任何位置调用blob.not \u owned \u by \u item\u owner

我想为一个属于另外两个模型的模型编写一个作用域。此范围应选择一个模型的值不等于其父模型值的所有记录。我下面所说的似乎应该有用:

Class Blob
 belongs_to :user
 belongs_to :item

 scope: :not_owned_by_item_owner, ->  { where.not(user_id: item.owner.id) }
end
但是,在控制器中的任何位置调用
blob.not \u owned \u by \u item\u owner
会导致
项目
未定义的局部变量或方法
错误。为什么无法识别
项目

解决方案1 解决方案2 或者,如果您更喜欢原始SQL:

scope :not_owned_by_item_owner, -> {
  joins(:item).where('blobs.user_id != items.owner_id')
}
# SELECT  "blobs".* FROM "blobs" INNER JOIN "items" ON "items"."id" = "blobs"."item_id" WHERE (blobs.user_id != items.owner_id) LIMIT $1

另外,我不认为有一个
ActiveRecord
本机解决方案可以解决这个问题,但如果有人找到,我也很感兴趣。上述解决方案1直接使用Arel。

有效。非常感谢你。看起来我的困惑在于何时使用
where.not
vs
=。从您的回答来看,似乎不应该使用
where.not
进行相等性比较。我是个笨蛋。
scope :not_owned_by_item_owner, -> {
  joins(:item).where('blobs.user_id != items.owner_id')
}
# SELECT  "blobs".* FROM "blobs" INNER JOIN "items" ON "items"."id" = "blobs"."item_id" WHERE (blobs.user_id != items.owner_id) LIMIT $1