Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 697
Midwire Avatar asked Oct 06 '10 18:10

Midwire


1 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 })
}
like image 154
wnm Avatar answered Oct 11 '22 11:10

wnm