检查我的Ruby on Rails routes.rb文件

时间:2011-10-10 02:57:42

标签: ruby-on-rails routes

我刚刚开始使用Ruby on Rails进行编程,我想知道你们中的一些人是否可以查看我目前使用的routes.rb文件并告诉我是否在考虑这个问题。

我知道RoR中的整个RESTful方法,我正在努力坚持下去,但我不确定我是否正常。到目前为止,我的应用程序只具有以下功能:

  • 用户注册
  • 用户激活(通过电子邮件链接)
  • 用户可以请求重新激活
  • 用户登录
  • 用户退出
  • 用户请求密码重置(收到电子邮件)
  • 基本UCP(更改电子邮件和密码)

我使用了很多redirect_to * _url和* _path,所以我想要很多命名路由。我试图明确声明只允许的路由。感谢您的投入。

MyApp::Application.routes.draw do
  get 'home' => 'pages#index', :as => 'home'
  get 'testing' => 'pages#testing', :as => 'testing'

  get 'register' => 'users#new', :as => 'register'
  post 'users/create'
  resources :users, :only => [
    :new,
    :create
  ]

  get 'activation' => 'activations#new', :as => 'activation'
  get 'activate/:token' => 'activations#activate', :as => 'activate'
  post 'activations/edit'
  resources :activations, :only => [
    :new,
    :activate,
    :edit
  ]

  get 'login' => 'sessions#new', :as => 'login'
  get 'logout' => 'sessions#destroy', :as => 'logout'
  get 'sessions/destroy'
  resources :sessions, :only => [
    :new,
    :create,
    :destroy
  ]

  get 'forgot_password' => 'resets#new', :as => 'forgot_password'
  post 'resets/create'
  get 'activate_password/:token' => 'resets#activate', :as => 'activate_password'
  put 'save_password' => 'resets#save', :as => 'save_password'
  resources :resets, :only => [
    :new,
    :create,
    :activate,
    :save
  ]

  get 'ucp' => 'ucp#show', :as => 'ucp'
  post 'ucp_update' => 'ucp#update', :as => 'ucp_update'
  resources :ucp, :only => [
    :show,
    :update
  ]

  root :to => 'pages#index'
end

1 个答案:

答案 0 :(得分:2)

当您使用resources时,它会自动为您创建命名路线。我不会浏览你的整个路径文件,但只举一个例子:

  get 'activation' => 'activations#new', :as => 'activation'
  get 'activate/:token' => 'activations#activate', :as => 'activate'
  post 'activations/edit'
  resources :activations, :only => [
    :new,
    :activate,
    :edit
  ]

可能是:

resources :activations, :only => [:new, :edit] do
  get 'activate', :on => :member
end

将生成new_activation_path,edit_activation_path和activate_activation_path

转到Rails Routing Guide,了解路线可以做的很多很酷的事情。例如,如果要为用户路径使用“register”而不是“new”:

 resources :users, :only => [:new, :create], :path_names => [:new => 'register']