views:

209

answers:

2

We have objects that we want to represent in stacks (think of stacking items in an MMO). There will be duplicate rows.

Let's say our owned_objects table looks like this.

user_id | object_id
1       | 27
1       | 27
3       | 46
3       | 46
5       | 59

I want the query to do

SELECT
  user_id,
  object_id,
  count(*) AS count
FROM owned_objects
GROUP BY
  user_id,
  object_id;

And return either the 3 distinct OwnedObjects (or even just getting the distinct Objects would work too) and a count associated with it.

I know this is possible with SQLAlchemy, but can you do it with ActiveRecord?

+1  A: 

How about …

@objects = user.objects.all(:select => "count(*) as count, objects.*", :group => :object_id)

… or similar?

You can then retrieve the counts by a dynamically created attribute on each object:

@object.first.count # the "stack depth" of the first object.

This assumes either a has_and_belongs_to_many :objects or a has_many :objects, :through => :owned_objects on user.

cwninja
Hmm, so I tried that and it returns the objects, and performs the correct query, but how does one retrieve the count from that call?
mikelikespie
It should be in the #count attribute of the respective objects.
cwninja
Don't think that's working because the reflection doesn't see a column called count. By `#count` you're referring to just the class method, `count`, courrect?
mikelikespie
No, count should be defined dynamically as an attribute on each returned object. ActiveRecord can be clever like that.
cwninja
Wierd. Maybe I'm doing something wrong.
mikelikespie
A: 

Found a solution, but not sure if it's the cleanest (hope it isn't).

Basically I created a SQL view that does that query and created a model for it. There's a plugin for rails that recognizes views on migrations.

mikelikespie