Gandalf StormCrow
Gandalf StormCrow

Reputation: 26212

Group sql with rails

If I wanted to display my object in a some hierarchy like display and if my object had properties like this :

parent_id, property_id, name

And I wanted to display it like this:

Parent
  -> Property
    -> Object name

So group them by parent first than by property, is this something I could do with the group

I've never done this before, I have a solution with ruby, but I'm not sure if this could be done faster with database.

Or maybe I'm looking this in a wrong way, how can I do this kind of sorting/nesting when all the information needed is on my object. Sure the ids are there which point to the records holding the information.

Update:

Here is my take on this :

MyObj.group_by{|m| m.parent.parent_name}
     .map{|k,v| { k => v.group_by(&:property).sort_by{|prop_array| prop_array.first.display_order } }}

It's hideous, it's unreadable, sometimes even I wonder what I've been trying to do here.

Upvotes: 0

Views: 57

Answers (3)

quarterdome
quarterdome

Reputation: 1581

You can not use ActiveRecord group for this, because group requires an aggregate function (like count, max, etc). What you are doing here is not an aggregate, you want to collect each and every object. If you would want to collect only counts, you could do this: Object.group(:parent_id, :property_id).count.

You can use sort to get the DB to do the sorting for you: Object.sort(:parent_id, :property_id). Then you can iterate and group them by in one linear array pass. This will likely be faster, but not really any less code.

Upvotes: 0

Andy Waite
Andy Waite

Reputation: 11086

Depending on your needs, you might want to consider using a gem for this: https://github.com/amerine/acts_as_tree

Upvotes: 1

errata
errata

Reputation: 26952

This is a pretty standard activerecord pattern. Offhand I don't see any reason to drop into sql. .group or .join should work fine. If you post more descriptive code I will try to be more specific. Play around with the existing data in the rails console to see what's possible.

Upvotes: 0

Related Questions