blog.robotex.de

Rails: Find model with associated record

Sometimes you need all the records, that have an associated record. I.e. you might want to have all People that have an address.

For this purpose you can add following scope to your model:

class Person < ActiveRecord::Base
  has_many :addresses

  scope :with, ->(type) { joins(type) }
end

Then you can use it like this:

Person.with(:addresses).all

Back