Negative regex constraint in Rails 3 routes
I have some rental listings that I want to be accessible as RESTful resource, but also have the index be filtered through an :area parameter, which could be a neighborhood or region. Given the 'rentals' resource, I'd like to have
/rentals
as well as the :area param filtering at the root level
/downtown
/westside
/some-neighborhood
etc.
I thought I could get this to work by putting the following near the bottom of my routes file:
resources :rentals
get ':area' => 'rentals#index', :area => /[a-zA-Z0-9\-]+/, :as => :area
But when I added Kaminari for pagination, it would auto-generate the pagination links to look something like
/rentals?area=downtown&page=2
when I'd rather have it look like
/downtown?page=2
In order to get Kaminari to use the named route version, the :area param needs to h开发者_JS百科ave priority, so I changed the routes to:
get ':area' => 'rentals#index', :area => /(?!rentals)[a-zA-Z0-9\-]+/, :as => :area
resources :rentals
But when I try to recognize the route in the console, I get:
ActionController::RoutingError: No route matches {:controller=>"rentals", :area=>"downtown"}
I'm not sure how to approach solving this, so any help would be appreciated.
You can use lambdas in your route constraints to solve this problem
match ':area' => 'rentals#index', :constraints => lambda{|req| !req.env["REQUEST_URI"].include? "rentals"}
精彩评论