Activerecord 如果相关记录不存在,如何使用Rails 3作用域在habtm联接表上进行筛选?

Activerecord 如果相关记录不存在,如何使用Rails 3作用域在habtm联接表上进行筛选?,activerecord,ruby-on-rails-3,scope,join,where,Activerecord,Ruby On Rails 3,Scope,Join,Where,我有一个作者模型,habtm:feed。使用Rails 3可以设置一个作用域,用于查找没有关联提要的所有作者 class Author < ActiveRecord::Base has_and_belongs_to_many :feeds scope :without_feed, joins(:feeds).where("authors_feeds.feed_id is null") end …似乎不起作用。感觉很简单。我在这里遗漏了什么?据我所知,ActiveRec

我有一个作者模型,habtm:feed。使用Rails 3可以设置一个作用域,用于查找没有关联提要的所有作者

class Author < ActiveRecord::Base

    has_and_belongs_to_many :feeds
    scope :without_feed, joins(:feeds).where("authors_feeds.feed_id is null")

end

…似乎不起作用。感觉很简单。我在这里遗漏了什么?

据我所知,ActiveRecord/Arel没有定义外部联接的方法。因此,您必须编写比正常情况多一点的SQL。像这样的事情应该可以做到:

    scope :without_feed, joins('left outer join authors_feeds on authors.id=authors_feeds.author_id').where('authors_feeds.feed_id is null')

我当然是在猜测你的表名和外键。但这应该会给你一幅图。

在Rails>=5中,你可以这样做:

范围:不含饲料,->{ 左外联接:馈送 .whereauthors_feed:{作者id:nil} } 经营范围:与_饲料,->{ 左外联接:馈送 .where.notauthors\u提要:{author\u id:nil} }
这感觉就像联接:提要正在执行一个内部联接,它只会在有提要的情况下选择一个作者?它确实在执行一个内部联接:选择作者。*从作者内部联接authors\u feed ON authors\u feed.author\u id=authors.id=authors\u feed.feed\u id其中authors\u feed.feed\u id为空我想要的是外部连接。有什么帮助吗?是的,就是这样。非常感谢。与此相反,只返回有X的作者,但一个简单的作者有很多地址,这个疯狂的东西从这篇文章拼凑而成,似乎起作用:范围:有地址,joinsleft外部联接按作者id从地址组中选择作者id作为地址上的地址。作者id=authors.id。其中address.author\u id不是nullYep,使用Arel是更好的方法。很高兴Rails 5+让我们这样做。