Home Pulling unique results through ActiveRecord based on uniqueness of a relation's attribute
 I am currently working on a fairly complex query to pull the top 5 entries within a table based on the following criteria: Which entries have the highest score Of those entries, make sure they all have the same attribute_type (fire, water, wind, etc.) Right now, I do not have my score system in place, so I figured I would do handle the first part related to using uniqueness of a specific related item. For some background info: Decklists have many Decks Decks have many Cards All Decklists have a Deck with the name, "Ruler" This Deck has an associated Card with an atribute_type I would like to pull all Decklists that contain a Deck called "Ruler" with a card matching the provided attribute_type. I've found a solution, but it uses Ruby enumerables, causing an insane number of queries and a very long page load. def self.top_five_by_attribute(attribute_type) existing_rulers = [] decklists = joins(:decks).joins(:cards).where(decks: {name: "Ruler"}, cards: { card_attribute: attribute_type} ).uniq decklists.find_all do |decklist| ruler = decklist.decks.find_by(name: "Ruler") if !existing_rulers.include?(ruler.cards.first.name) existing_rulers << ruler.cards.first.name puts existing_rulers decklist end end end  Would anyone know how to condense this into a single ActiveRecord query?