How to add urls dynamically in Ruby On Rails? -


given complex url, want give user shortened , nice url. example, if user gives me url1, return user url named www.something.com/some-name.

if user gives me url2, return user url named www.something.com/some-other-name. (i store provided url , matching url in database)

i plan receive shortened , find corresponding url in database, , redirect users original url. how should route www.something.com/some-name correct controller in ruby on rails? , how add these routes dynamically?

this easy, first create model, example called shorturl, 2 fields, example short_url , original_url.

then create controller, example call short_urls_controller , add routes, if put route @ begining , make generic, match routes , app won't function correctly, if app has other routes , not made purpose.

get /:short_url, to: 'short_urls#go' 

or if want make sure plays nice others add small prefix

get /u/:short_url, to: 'short_urls#go' 

then controller, if have devise or authentication, make sure skip authentication here, u don't want people hitting short url getting 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 handle wrong urls, because find_by fail if url not existing, add gracefully fail 404.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -