Friday, July 15, 2011

[Rails] Re: what is the difference between using group_by in a scope as opposed the controller?

On Jul 14, 1:47 pm, "frankjmat...@gmail.com" <frankjmat...@gmail.com>
wrote:
> > frankjmat...@gmail.com> wrote:
> > > 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>
>
> > 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
>
> 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


> Thanks again,
> - FJM

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate