1

I have a model like this:

class Year < ActiveRecord::Base
  extend FriendlyId
  friendly_id :year, use: :slugged

  has_many :events

I want in my controller, to get all the years that have at least one event. How can I do that?

I was trying to make this:

 Year.includes(:events).first.events
  Year Load (0.3ms)  SELECT  `years`.* FROM `years`  ORDER BY `years`.`id` ASC LIMIT 1
  Event Load (0.3ms)  SELECT `events`.* FROM `events` WHERE `events`.`year_id` IN (1)
 => #<ActiveRecord::Associations::CollectionProxy []> 

But this is returning empty sets.

Fernando Maymone
  • 665
  • 1
  • 8
  • 17

1 Answers1

4

Join with events. This gives you all your years except those ones that don't have an event attached.

Year.joins(:events).distinct
Ursus
  • 29,643
  • 3
  • 33
  • 50