jayp
jayp

Reputation: 362

Need ActiveRecord query to find parent that has specific child record along with others

I'm using Ruby on Rails and Postgres and I have three tables: Event, Speaker, and Event_Speaker (the last of which enables a two-way has_many, through relationship between Event and Speaker).

On an individual speaker's show view, I'm trying to display not only all of the events featuring that speaker, but also the count of how many events feature only that speaker (versus events featuring that speaker along with one or more others).

I can't seem to come up with an ActiveRecord query that is able to accomplish this latter part. Any ideas?

Upvotes: 0

Views: 394

Answers (2)

j-dexx
j-dexx

Reputation: 10406

So to give an answer based on Mauricio Moraes' comment.

Migration

def change
  add_column :events, :speakers_count, :integer, default: 0
end

Model

class EventSpeaker
  belongs_to :event, counter_cache: :speakers_count
  belongs_to :speaker
end

So now you can do a simple query

speaker = Speaker.first
only_speaker_events = speaker.events.where(speakers_count: 1)

Upvotes: 2

Kris
Kris

Reputation: 19948

What about using select. Load all events for the speaker from the database and then reject any which have more than one speaker.

speaker.events.select { |e| e.speakers.count == 1 }

Upvotes: 1

Related Questions