Distinct Active Records In Has_many Through Associations - Lugo Labs

Lugo Labs
  • Products Iconly Tracker
  • Open Source Circles Loda button Datepicker skins Icofont Iconly Rails Skins
  • Tools Caret Flat Slider Charicons
  • Blog Blog Reading List
  • Contact
Distinct Active Records in has_many through associations

7 February 2017

Ruby on Rails

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.

Tag » Activerecord Unique Associations