Given a model Event which
has_many :user_events
And a model UserEvent which
belongs_to :event
I could get the related user_events from a single event object, like so:
event = Event.find(1)
user_events = event.user_events
But is there an equivalent relation accessor for a collection of events? For example:
events = Event.where(:event_type => 'fun')
user_events = events.user_events
Which would return the user_events which belong to any ‘fun’ events using something like.
SELECT user_events.* FROM user_events JOIN events on (events.id = user_events.event_id) where (events.event_type = 'fun');
No, there isn’t a relation accessor for a collection of events.
In the meantime, you can do:
The
user_eventsare eager loaded thanks toincludes(:user_events). That’s commonly used.We use the same logic when we do things like that (simplified):