On Sep 28, 2010, at 10:49 AM, Pete wrote:

> Hi,
> 
> I am currently a little confused with trying to manipulate a named
> scope that I currently have.
> I use this named scope with a table-plus, and it works very nicely,
> but I want to trim it down a little.
> 
> I have two associated models e.g
> 
> Catalogue,
> 
> has_many :articles
> 
> Article:
> 
> belongs_to :catalogue
> 
> my named scope looks like this (in Class Article)
> 
> :finished_articles, {  :conditions => [ :finished => true ] }
> 
> This works fine on it's own, but I need to trim it to show only the
> most recent finished article per catalogue (based on created_at field)
> 
> I have tried to use two named scopes, the other looking like this:
> 
> :limited, { :group => "catalogue_id" }
> 
> which does only leave one entry per catalogue, but rather than being
> the most recent entry it is the first created.
> 
> I just want to be able to reverse this order, but I can't seem to
> figure out how to do this (I have a default order already set, but
> this only seems to affect the scope after it has been rendered..) Also
> setting the order does not seem to have an effect on how the instances
> are gathered from the database.

I think you're going to have to try a different approach - at least in MySQL, 
'GROUP BY' doesn't promise anything about fields that vary amongst elements of 
the group:

http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html

You'll probably be better off doing this in a more Rails-flavored way:

class Catalogue

  has_many :articles
  has_one :recent_article, :conditions => { :finished => true }, :order => 
'articles.created_at DESC', :class_name => 'Article'

end

Then you could get them all by:

Catalogue.find(:all, :include => :recent_article)

which will eager-load the whole bunch in one go.

This *should* work, but I haven't tried it - and I'm not 100% sure if that 
eager-loading trick will work...

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Hobo 
Users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/hobousers?hl=en.

Reply via email to