Topic: how to order acts_as_taggable results

I'm creating an event website with tags using the acts_as_taggable plugin.  I've linked up each tag with a method that displays all events with that tag.

  def tag
    @events = Event.find_tagged_with(params[:id])
    render :action => 'index'
  end

but I can't figure out how to get the resultant events listed in order by date.  I thought I could just add

  :order => 'date'

onto the @events line, but RoR doesn't seem to like that.  any advice?

Re: how to order acts_as_taggable results

You may have to just sort them after they're fetched:

@events = Event.find_tagged_with(params[:id]).sort_by(&:date)

Alex

Re: how to order acts_as_taggable results

I don't use the plugin and don't know what exactly #find-tagged_with does, but i guess this could do the job:

@events = Event.find_tagged_with(params[:id],:order => "tags.date")

Last edited by Duplex (2007-07-22 17:10:59)

Re: how to order acts_as_taggable results

thanks so much Alex, that totally did the trick!  I was looking for something exactly like that, I just didn't know about "sort_by", is that in the API or somewhere I missed?  and what is the ampersand all about?  thanks a ton!

Re: how to order acts_as_taggable results

Yeah sort_by is part of Enumerable, which is an extension to the Array class. You can find most of them (including sort_by) in the Ruby docs, but a couple of useful extras are currently Rails specific and can be seen here.

As for the &: thing, its just another one of the shortcuts Rails provides for us lazy programmers wink:

@events.sort_by(&:date) 

# is the same as

@events.sort_by {|event| event.date}


Alex

Re: how to order acts_as_taggable results

awesome, thanks!