lacostenycoder
lacostenycoder

Reputation: 11216

Rails ActiveRecord scoped many to many query

In my models Event and Artist are both HABTM relations. Events are default scoped to current events by date so to only show events that haven't happened yet. I'm trying to write a method or scope to get all from Artist that have no current events. I tried ActiveRecord relation

none = Artist.where{|a| a.events.default_scope.count == 0}

But this returns

ActiveRecord::QueryMethods::WhereChain

And then I can't get the actual objects to work with. Then when I iterate over .all it's very slow because there's a ton of data in the models.

Artist.all.select{|a| a.events.default_scope.count == 0}

What is a faster or better way to handle this?

Upvotes: 0

Views: 101

Answers (1)

Baldrick
Baldrick

Reputation: 24340

Use a LEFT JOIN on events and the join table, add the condition to include only current events, and get only artists where there is no events:

scope :no_events, -> {
  joins('LEFT JOIN artists_events ON artists.id = artists_events.artist_id')
  .joins('LEFT JOIN events ON events.id = artists_events.event_id')
  .where([here the condition for current events])
  .where('events.id IS NULL') 
}

You may need to add a distinct

Upvotes: 1

Related Questions