What is the difference between using group_by in a scope as opposed the controller?

In my controller I have this and it works.

@grouped_by_assignable = collection.order(“updated_at desc”).group_by
{ |assignment| assignment.assignable }

trying to refactor it into a scope on the model as such

scope :grouped_by_assignable, order(“updated_at desc”).group_by { |
assignment| assignment.assignable }

yields

ArgumentError: Unknown key: #Project:0x00000102dd5d80

Any advice?

Thanks,

  • FJM

On Thu, Jul 14, 2011 at 9:40 AM, [email protected] <
[email protected]> wrote:

yields

ArgumentError: Unknown key: #Project:0x00000102dd5d80

group_by is an Array method. You can try doing this instead

scope :recently_updated, order(“updated_at desc”)

def self.grouped_by_assignable
recently_updated.group_by { |assignment| assignment.assignable }
end

But beware, this method would return an array not an AR relation

[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.

end

But beware, this method would return an array not an AR relation

Ah, makes perfect sense… what could I do if I still wanted to create
an AR relation? Is this a use case for #group? I tried that as well
but I couldn’t get it to group the way I needed it to… I think that
because assignable is polymorphic I need to group by assignable_id and
assignable_type… How can I accomplish that?

Thanks again,

  • FJM

On Jul 14, 1:47pm, “[email protected][email protected]
wrote:

end

But beware, this method would return an array not an AR relation

Ah, makes perfect sense… what could I do if I still wanted to create
an AR relation? Is this a use case for #group? I tried that as well
but I couldn’t get it to group the way I needed it to… I think that
because assignable is polymorphic I need to group by assignable_id and
assignable_type… How can I accomplish that?

I would have thought that ‘group by assignable_type, assignable_id’
would do the trick

Fred

On Thu, Jul 14, 2011 at 8:47 PM, [email protected] <
[email protected]> wrote:

yields

ArgumentError: Unknown key: #Project:0x00000102dd5d80

group_by is an Array method. You can try doing this instead

had to correct this, group_by is an Enumerable method.

but I couldn’t get it to group the way I needed it to… I think that
because assignable is polymorphic I need to group by assignable_id and
assignable_type… How can I accomplish that?

I’m pretty sure that you can’t get an array of hashes out of an AR query
so I guess this can’t be done on the database side.

http://groups.google.com/group/rubyonrails-talk?hl=en.