Say I have this:
class Post < ActiveRecord::Base
has_many :relationships, :as => :parent
has_many :images, :through => :relationships
end
class Relationship
belongs_to :parent, :polymorphic => true
belongs_to :child, :polymorphic => true
end
class Image < ActiveRecord::Base
has_many :relationships, :as => :child
has_many :posts, :through => :relationships
end
I want to then, as leanly as I can, get back a hash from this call:
Relationship.all(:select => "parent_id, child_id")
...that looks like this:
{:parent_id_1 => [:child_id_1, :child_id_7] ...}
{1 => [1, 7]} #...
Instead, that above call gives me this:
[{"parent_id"=>"1", "child_id"=>"1"}{"parent_id"=>"1", "child_id"=>"7"}...]
So then I have to merge them, and I'm getting a lot of stuff back I don't need. Is there a way to get back something like {1 => [1, 7]}
using pure SQL?
Update
I just did this for now, still looking for a cleaner solution:
[{"parent_id"=>"1", "child_id"=>"1"}{"parent_id"=>"1", "child_id"=>"7"}...].inject({}) do |result, node|
result[node["parent_id"]] ||= []
result[node["parent_id"]] << node["child_id"]
result
end