How to use Rails 3 scope to filter on habtm join table where the associated records don't exist?

Viewed 9148

I have an Author model which habtm :feeds. Using Rails 3 want to setup a scope that finds all authors that have no associated feeds.

class Author < ActiveRecord::Base

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

end

...doesn't seem to work. It feels like a simple thing. What am I missing here?

2 Answers

In Rails >= 5, you can do it like this:

scope :without_feed, -> {
  left_outer_joins(:feeds)
  .where(authors_feeds: { author_id: nil })
}

scope :with_feed, -> {
  left_outer_joins(:feeds)
  .where.not(authors_feeds: { author_id: nil })
}
Related