ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

Get param from URL in Rails


Using Rails 3.1. I have some pages that render same layout, except the contents are based on types:

near_england.html.erb
near_scotland.html.erb

So usually the full URLs are:

http://localhost/shops/near_england
http://localhost/shops/near_scotland

I could have constructed the URL as follows:

http://localhost/shops/near?country=england
http://localhost/shops/near?country=scotland

And make my query easier by getting the parameters, but I am such a SEO freak that I think near_england and near_scotland would be better in SEO.

Is there any way that I can strip off the nearby_ and return england as a param so that I can put this in my query?

Thank you.


Solution

  • What you need is a custom route, mapping to a single view. Add something like this in your route definition:

    match "near_:country" => "countries#near"
    

    In your action, you can retrieve the parameter using params[:country]