Reputation: 327
Given a complex url, I want to give the user a shortened and nice url. For example, If the user gives me url1, I will return the user a url named www.something.com/some-name.
If the user gives me url2, I will return the user a url named www.something.com/some-other-name. (I will store the provided url and its matching url in the database)
I plan to receive the shortened and find the corresponding url in the database, and redirect the users to the original url. But how should I route the www.something.com/some-name to the correct controller in Ruby on Rails? And How do I add these routes dynamically?
Upvotes: 1
Views: 482
Reputation: 42799
This is easy, first create a model, for example called ShortUrl
, with two
fields, for example short_url
and original_url
.
Then create the controller, for example call it short_urls_controller
and add it to
the routes, but if you put the route at the very begining and make it very
generic, it will match all the routes and your app won't function correctly,
that is if the app has other routes and not just made for this purpose.
get /:short_url, to: 'short_urls#go'
or if you want to make sure it plays nice with others then just add a small prefix
get /u/:short_url, to: 'short_urls#go'
Then the controller, if you have devise or any authentication, make sure you skip that authentication here, u don't want people hitting your short url then getting a please login alert
def ShortUrlsController < ApplicationController
skip_before_action :authenticate_user!
def go
url = ShortUrl.find_by(short_url: params[:short_url])
redirect_to url.original_url
end
end
You should also handle wrong urls, because that find_by
will fail if the url was not existing, so add something to gracefully fail with a 404.
Upvotes: 1