【问题标题】:Rails 3 routing - what's best practice?Rails 3 路由 - 最佳实践是什么?
【发布时间】:2010-05-27 09:27:57
【问题描述】:

我正在试用 Rails,但偶然发现了路由问题。

我有一个名为“Account”(单数)的控制器,它应该为当前登录的用户处理各种设置。

class AccountController < ApplicationController
    def index
    end

    def settings
    end

    def email_settings
    end
end

如何以适当的方式为此设置路线?目前我有:

match 'account(/:action)', :to => 'account', :as => 'account'

然而,这不会自动产生像 account_settings_path 这样的方法,而只会产生 account_path

有没有更好的做法?请记住,Account 控制器并不代表 ActiveModel 的控制器。

如果这实际上是最佳做法,我将如何在我的视图中为操作生成链接? url_to :controller =&gt; :account, :action =&gt; :email_settings ?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    要在视图中使用命名 URL,您需要在 routes.rb 中指定要命名的每个路由。

    match 'account', :to => 'account#index'
    match 'account/settings', :to => 'account#settings'
    match 'account/email_settings', :to => 'account#email_settings'
    

    或者

    scope :account, :path => 'account', :name_prefix => :account do
      match '', :to => :index, :as => :index
      match 'settings', :to => :settings
      match 'email_settings', :to => :email_settings
    end
    

    两者都一样,只是选择问题。但我确实认为第一种方法是最干净的,即使它不是 DRY。

    【讨论】:

    • 另外,你不必使用:to,也可以这样:match 'account' =&gt; 'account#index'
    【解决方案2】:

    您也可以将其定义为资源上的集合:

      resources :login do
        collection { get :reminder, :test }
      end
    

    当然,这也定义了默认的 CRUD 操作。我目前只将其中两个用于我的非实际模型控制器,但我认为/预计额外的路由不会有任何问题。

    【讨论】:

    • 那加了很多额外的路由没用
    猜你喜欢
    • 2018-07-09
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2015-11-21
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多