Here's my dilemma: I have two types of routes which are semantically very different, and should go to different controllers.
ny/new-york/brooklyn/cleaners # should go to a list 开发者_如何学Goof cleaners for a neighborhood
ny/new-york/cleaners/mrclean # should go to an individual cleaner's page
Note that "brooklyn" and "cleaners" here are just examples. The app has many service types (e.g. "cleaner") and many neighborhoods, so it's impossible to hard-code a list of either into a regular expression and use that to distinguish the two routes.
Is it possible to involve an arbitrary method, which accesses ActiveRecord models, in the routing decision? I'm using Rails 2.3.8.
Edit : new answer with dynamic services
Looking at this blog entry it seems possible to use ActiveRecords in the routes.
Maybe you could do something like this :
service_names = Service.all.map(&:short_name) # assuming the property 'short_name' is the value used in urls
service_names.each do |service_name|
map.connect ':state/:city/#{service_name}/:company' :controller => ‘company’, :action => ‘show’ # to show the company's page
map.connect ':state/:city/:neighborhood/#{service_name}_finder' :controller => ‘company_finder’, :action => ‘find’ # to list the companies for the given service in a neighborhood
end
That should still prevent conflicts since the routes for a certain service is before a route for a neighborhood
Old bad answer
Can't you use the two following routes ?
map.connect ':state/:city/cleaners/:cleaner' :controller => ‘cleaners’, :action => ‘show’ # to show the cleaner's page
map.connect ':state/:city/:neighborhood/cleaners' :controller => ‘cleaner_finder’, :action => ‘find’ # to list the cleaners of a neighborhood
In your controller, you should be able to retrieve :state, :city and others value using params[:state], params[:city], etc.
Putting the :state/:city/cleaners/:cleaner on the first line should prevent ambiguity.
精彩评论