Rails: Find model with associated record

Mittwoch, 07. Juni 2017, 10:26 Uhr | roberto@vasquez-angel.de |

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