【问题标题】:Multiple Nested Routes, is there a better way to do this?多个嵌套路由,有没有更好的方法来做到这一点?
【发布时间】:2009-11-13 01:09:32
【问题描述】:

所以在我的 rails 应用程序中,我有两个资源(租金和预订)属于一个用户。这是我的 routes.rb 中用于设置嵌套路由的代码。

  map.resources :users, :has_many => :reservations, :shallow => true
  map.resources :users, :has_many => :rentals, :shallow => true
  map.resources :rentals, :only => [:index]
  map.resources :reservations, :only => [:index]

有没有更好的方法来做到这一点。我已经做了一些谷歌搜索,但我找不到明确的答案。

提前致谢。

-射线

【问题讨论】:

    标签: ruby-on-rails routing nested-resources


    【解决方案1】:

    您的方法为用户复制了路由,您可以通过运行rake routes 看到。您可以通过将块传递给map.resources 来解决此问题:

    map.resources :users, :shallow => true do |user|
      user.resources :reservations
      user.resources :rentals
    end
    

    创建的嵌套路由将假定您始终希望以嵌套方式访问这些资源。

    如果您确实需要您定义的所有路线(包括非嵌套的出租和预订索引),那么您需要添加:

    map.resources :rentals, :only => [:index]
    map.resources :reservations, :only => [:index]
    

    而且我不知道有什么 DRYer 方法可以做到这一点。

    【讨论】:

      【解决方案2】:

      将两个资源嵌套在users下:

        map.resources :users, :shallow => true do |users|
          users.resources :reservations, :only => :index
          users.resources :rentals, :only => :index
        end
      

      编辑:抱歉,忘记了 :shallow 选项。

      【讨论】:

      • 这不会将所有路由创建为原始路由。 OP 有一个完整的嵌套路由列表,外加一个非嵌套路由(索引)。
      • ScottJ 是对的,我的代码 sn-p 只会产生 OP 想要的路由子集。
      【解决方案3】:

      您可以使用块定义嵌套路由

      map.resources :users, :shallow => true do |user|
        user.resources :reservations, :only => [:index]
        user.resources :rentals, :only => [:index]
      end
      

      我觉得这种方式更清晰一些,当您需要在其中一个嵌套资源上添加其他选项时,可以更轻松地进行调整。

      不同的选项和详细信息在ActionController Resources API page

      【讨论】:

      • 与我在 kchau 的回答中留下的评论相同:这不会像原来一样创建所有路线。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2011-03-10
      相关资源
      最近更新 更多