Lugo Labs

Distinct Active Records in has_many through associations

When working on our web podcast player, Lugano.io, I had to build these Ruby on Rails models:

ruby
# app/models/author.rb
class Author < ApplicationRecord
  has_many :authorships,
  has_many :podcasts, through: :authorships
end

# app/models/podcast.rb
class Podcast < ApplicationRecord
  has_many :authorships
  has_many :authors, through: :authorships
end

# app/models/authorship.rb
class Authorship < ApplicationRecord
  belongs_to :author
  belongs_to :podcast
end

The Podcast and Author models are associated via a many to many relationship. On a query I wanted to get the distinct authors of a podcast. I was about to use some complicated SQL, when I remembered that ActiveRecord provides this out of the box. Just change the podcast code to this:

ruby
# app/models/podcast.rb
class Podcast < ApplicationRecord
  has_many :authorships
  has_many :authors, -> { distinct }, through: :authorships
end

This will add a DISTINCT to all the related queries, and works beautifully. Just remember to add the lambda before the :through option. You may want to check the Ruby on Rails Guides for more info.

--

And since this is a quick post, here's a quick joke for you:

- Daddy did you know that girls are smarter than boys?
- No, I didn’t know that.
- There you go.