Home Pulling unique results through ActiveRecord based on uniqueness of a relation's attribute
Reply: 0

Pulling unique results through ActiveRecord based on uniqueness of a relation's attribute

user1619
1#
user1619 Published in April 24, 2018, 6:28 am

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?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.317415 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO