为url shortener设置路由

时间:2014-11-19 01:38:07

标签: ruby-on-rails ruby ruby-on-rails-4 routing

我正在尝试创建一个用作网址缩短器的rails应用程序。我在配置路由时遇到问题。如何允许用户访问我的网站并将其重定向到他们输入的网址上的网站。IE mysite.com/any_random_url。

的routes.rb

Rails.application.routes.draw do
  get 'home/index'
  get 'home/about'
  get 'home/:id' => 'home#show'    

  root 'home#show/:id'
  ..

home_controller.rb

class HomeController < ApplicationController
  def index
  end

  def about
  end

  def show
    url = params[:id]
    @url = ShortUrl.where(["url = ?", url]).first
    if @url.nil?
      return redirect_to action: 'index', status: 307
    else
      return redirect_to @url
    end
  end  

1 个答案:

答案 0 :(得分:2)

如果您希望能够使用多个斜杠,则需要使用以下内容:

get '*id', to: 'home#show'

如果您只想要一个子路径(即/ 23af1),可能最好使用它:

get ':id', to: 'home#show'

您可以在Rails Guide

中找到更多信息