I am looking toward writing a scope that returns all records that do not have a particular association.
foo.rb
class Foo < ActiveRecord::Base has_many :bars end
bar.rb
class Bar < ActiveRecord::Base belongs_to :foo end
I want a scope that can find all of the Foo's
that dont have any bars
. It's easy to find the ones that have an association using joins
, but I haven't found a way to do the opposite.
The Arel::Table object acts like a hash which contains each column on the table. The columns given by Arel are a type of Node , which means it has several methods available on it to construct queries. You can find a list of most of the methods available on Node s in the file predications.
Rails 4 makes this too easy :)
Foo.where.not(id: Bar.select(:foo_id).uniq)
this outputs the same query as jdoe's answer
SELECT "foos".* FROM "foos" WHERE "foos"."id" NOT IN ( SELECT DISTINCT "bars"."foo_id" FROM "bars" )
And as a scope:
scope :lonely, -> { where.not(id: Bar.select(:item_id).uniq) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With