Note that there are some explanatory texts on larger screens.

plurals
  1. POParent entity sorted by votes difference
    primarykey
    data
    text
    <p>I have three models that look like this (I just left the stuff important for the question):</p> <pre><code>class Symbol &lt; ActiveRecord::Base has_many :mnemonic end class Mnemonic &lt; ActiveRecord::Base belongs_to :symbol has_many :mnemonic_votes end class MnemonicVote &lt; ActiveRecord::Base belongs_to :mnemonic attr_accessible :vote_up end </code></pre> <p>:vote_up is of boolean type which if true means someone upvoted the mnemonic, and if false means someone downvoted it.</p> <p>I would like to get top three mnemonics by vote difference. Let's say there are 5 mnemonic records in the database with the following number of up/down votes (MnemonicVote records with true/false as :vote_up field):</p> <pre><code>mnemonic up down total mnemonic1 3 2 1 mnemonic2 17 3 14 mnemonic3 2 5 -3 mnemonic4 11 7 4 mnemonic5 5 5 0 </code></pre> <p>I would like to get the following three mnemonics (with counts) by descending order:</p> <pre><code>mnemonic2 14 mnemonic4 4 mnemonic1 1 </code></pre> <p>I wrote this actual code which gives me the result I want, but I am aware it sucks and I don't like how I did it because the data gets grouped and sorted <em>after</em> all the MnemonicVote records associated with a certaing Mnemonic record are fetched from the DB:</p> <pre><code>@mnemonics = Mnemonic.where(symbol_id: self.id) # here I fetch all Mnemonics associated with Symbol table @mnemonics.sort_by { |mnemonic| mnemonic.votes_total }.reverse! return @mnemonics.take(3) </code></pre> <p>where mnemonic.votes_total is a calculated attribute on Mnemonic object. I would like to get the same result by using a single AR (or even SQL) query. How can this be accomplished? Thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload