Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To get a list of user IDs with more than one purchase, you can do the following, which will access just one table:</p> <pre><code>user_ids = PurchasedDeal.count(:group =&gt; :user_id, :having =&gt; 'count_all &gt; 0').keys </code></pre> <p>Subsequently, you can fetch all these users with:</p> <pre><code>users = User.find user_ids </code></pre> <hr> <p>Things can be sped up with a counter cache. In your user model, add the option <code>:counter_cache =&gt; true</code> to the <code>has_many</code> association for purchased deals. You'll need an extra integer column on your users table and initialize, which might look as follows in a migration:</p> <pre><code>add_column :users, :purchased_deals_count, :integer, :null =&gt; false, :default =&gt; 0 User.each { |u| User.reset_counters u, :purchased_deals } </code></pre> <p>Once that's out of the way, it becomes a lot simpler:</p> <pre><code>users = User.all :conditions =&gt; 'purchased_deals_count &gt; 0' </code></pre> <p>Rails will keep the column up-to-date for you, with most standard operations.</p> <hr> <p>To get the total price will always involve a join. Or you can build a hash of deal prices and do the tedious processing in Ruby. I'm no SQL expert, but you can potentially get rid of the join by storing the price with the PurchasedDeal. Otherwise, here's how to do it with a join:</p> <pre><code>user_id_to_price = PurchasedDeal.sum 'deal.price', :include =&gt; :deal, :group =&gt; :user_id </code></pre> <p>You could filter that on just the users you want by adding something like <code>:conditions =&gt; ['user_id IN (?)', users]</code>. (Where <code>users</code> can be a list of IDs, but also User objects.)</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.
 

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