Question

So I have this object, let's call it Dog, and this other object, let's call it Collar.

class Dog < ActiveRecord::Base
  has_one :collar
end

class Collar < ActiveRecord::Base
  belongs_to :dog
end

Can I get a list of dogs that have collars? Ideally in a slightly less awkward way than the following:

Dog.joins(:collar).where(Collar.arel_table['id'].not_eq(nil))

As a note to those who might wonder about the "arel_table" bit, it is the DB-agnostic way of saying "IS NOT NULL".

Was it helpful?

Solution

You can just use joins directly

Dog.joins(:collar)

This will return dogs which have collar.

There is even no need to add uniq because this is has_one relation so no duplicate dogs will be returned.

OTHER TIPS

and what about just create scope in Collar or Dog model something like:

scope :with_something, where( "foreign_key IS NOT NULL" )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top