views:

24

answers:

1

I'm writing a Conference listing website in Rails, and came across this requirement:

chain, in no particular order, a URL to find events, such as:

/in/:city/on/:tag/with/:speaker

or rearranged like

/in/:city/with/:speaker/on/:tag

i can handle these fine one by one. is there a way to dynamically handle these requests?

A: 

i achieved it with the following (excuse some app-specific code in there):

routes.rb:

  map.connect '/:type/*facets', :controller => 'events', :action => 'facets'

events_controller.rb:

def facets
    @events = find_by_facets(params[:facets], params[:type])
    render :action => "index"

  end

application_controller.rb:

def find_by_facets(facets, type = nil)
query = type.nil? ? "Event" : "Event.is('#{type.singularize.capitalize}')"
for i in (0..(facets.length - 1)).step(2)
  query += ".#{facets[i]}('#{facets[i+1].to_word.capitalize_words}')"
end
@events = eval(query)

end

event.rb:

  named_scope :in, lambda { |city| { :conditions => { :location => city } } }

  named_scope :about, lambda {
      |category| {
          :joins => :category,
          :conditions => ["categories.name = ?", category]
      }
  }

  named_scope :with, lambda {
      |speaker| {
          :joins => :speakers,
          :conditions => ["speakers.name = ?", speaker]
      }
  }

  named_scope :on, lambda {
      |tag| {
          :joins => :tags,
          :conditions => ["tags.name = ?", tag]
      }
  }

  named_scope :is, lambda {
      |type| {
          :joins => :type,
          :conditions => ["types.name = ?", type]
      }
  }

this gives me URLs like /conferences/in/salt_lake_city/with/joe_shmoe or /lectures/about/programming/with/joe_splo/, in no particular order. win!

Jason Lynes