Distinct Active Records In Has_many Through Associations - Lugo Labs
Maybe your like
- Products Iconly Tracker
- Open Source Circles Loda button Datepicker skins Icofont Iconly Rails Skins
- Tools Caret Flat Slider Charicons
- Blog Blog Reading List
- Contact
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 endThe 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 endThis 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
-
Get All Unique Associations In Rails 5 - Stack Overflow
-
Active Record Associations - Ruby On Rails Guides
-
Distinct (ActiveRecord::Associations::CollectionProxy) - APIdock
-
Autosaving Associations Twice In Rails 6.0.3 Violates Uniqueness
-
Ruby On Rails Tutorial => .distinct (or .uniq)
-
ActiveRecord Associations And You - Mutually Human
-
Rails Validation: Pitfalls In Validating Uniqueness With Active Record
-
How To Use Associations And Class Names In Ruby On Rails?
-
The Trouble With `has_one` - Medium
-
ActiveRecord::Associations::ClassMethods | RailsDoc(β)
-
Rails Models Cheatsheet - Devhints
-
Sinatra Activerecord Associations
-
Rails: How To Set Unique Interchangeable Index Constraint
-
Improving Database Performance And Overcoming Common N+1 ...