Chris Bloom
Chris Bloom

Reputation: 3554

How can I catch and reroute a url with a specific querystring parameter in Rails 3

i have a controller named PagesController which used to have an action named contest. In this action I would check for the existence of a thanks param and serve up a thank you page if it was present. I've since abstracted that single action into a model and controller of it's own and I now want to redirect any requests for /contest?thanks to /contests/thanks. What is the best way to do this? So far I've tried the following in my routes.rb file, but it doesn't work:

# Redirect old URLs
match '/contest' => redirect("/contests")
match '/contest?thanks' => redirect("/contests/thanks")

Upvotes: 1

Views: 386

Answers (2)

SamStephens
SamStephens

Reputation: 5861

If you want to deal with this entirely in routes.rb this route would work:

match '/contest' => redirect { |params, request|
  if request.params.has_key?(:thanks)
     "/contests/thanks"
  else
     "/contests"
  end
}

Upvotes: 2

Hertzel Guinness
Hertzel Guinness

Reputation: 5950

You can redirect from the controller -

config/routes.rb:

match "/contest" => "contest#old_route"

app/controllers/contest_controller.rb:

def old_route
    if params[:thanks]
       redirect_to "/contests/thanks"
    else
       redirect_to "/contests"
    end
end

HTH

Upvotes: 1

Related Questions