Reputation: 427
I`m looking to implement links that fit a certain format (seo purposes).
Here`s an example:
match '/activities-Palmdale-California', :to => 'explores#activity_by_city', :location=>'Palmdale-California'
Where the location changes for each city+state.
Is there I way to dynamically loop through an array of cities & states (predefined) in the routes file, without creating additional models etc. ?
Upvotes: 1
Views: 2923
Reputation: 11710
You can have parameters in your routes, so something like the following should work:
match "/activities-:location", :to => 'explores#activity_by_city'
and the location
should be sent to your controller action in params[:location]
. If you want to limit the urls your application will accept to just the locations in a predefined array (we'll call it ValidLocations
), you can do it either in the route with the :constraints
option:
match "/activities-:location", :to => 'explores#activity_by_city', :constraints => proc { |req| ValidLocations.include?(req.params[:location]) }
or in the controller:
def activity_by_city
...
unless ValidLocations.include?(params[:location])
flash[:error] = "Invalid location."
redirect_to ...
return
end
...
end
Upvotes: 3