【问题标题】:correctly configuring nested resources with shallowing使用浅化正确配置嵌套资源
【发布时间】:2016-01-13 14:33:22
【问题描述】:

我在嵌套资源和文档中遇到了第一个问题

http://guides.rubyonrails.org/routing.html#limits-to-nesting

我不完全能够弄清楚如何理解这一点,以及如何将其正确应用于我的情况,目前我的东西是这样设置的:

  resources :stores do
    resources :locations do
      resources :business_hours
    end
  end

现在我想限制嵌套,他们推荐的方式,但我不确定如何实现这一点,因为地点属于商店,营业时间属于地点。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    rails 文档实质上是说,通过上面的资源配置,您将拥有一个在您的网页上看起来像这样的 url。

    mywebapplication.com/stores/1/locations/1/business_hours/1

    为您的代码使用相应的 rails 辅助方法

    stores_locations_business_hours_url

    现在这并没有什么问题,你可以这样做,但你会开始遇到繁琐的问题,尤其是你的 business_hours 控制器。原因是因为对于您的控制器,您必须传入以下每个 @model 对象。你必须做类似的事情

    stores_locations_business_hours_url([@store,@location,@business_hour])

    访问页面。要限制这一点,您需要执行以下操作:

    resources :stores do
        resources :locations, shallow: true
    end
    
    resources :locations do
        resources :business_hours
    end
    

    所以现在 URL 将像 mywebapplication.com/locations/1 而不是 mywebapplication.com/stores/1/locations/1,现在您的营业时间 URL 将更深一层。这就是文档的含义。

    【讨论】:

      【解决方案2】:

      要满足 Rails 的要求,您只需将 shallow: true 添加到每个嵌套的 resources:

      resources :stores do
        resources :locations, shallow: true do
          resources :business_hours, shallow: true
        end
      end
      

      正如他们所说,这会产生“用最少的信息来唯一标识资源的路由”,如下所示:

                          Prefix Verb   URI Pattern                                          Controller#Action
         location_business_hours GET    /locations/:location_id/business_hours(.:format)     business_hours#index
                   business_hour GET    /business_hours/:id(.:format)                        business_hours#show
                 store_locations GET    /stores/:store_id/locations(.:format)                locations#index
                        location GET    /locations/:id(.:format)                             locations#show
                          stores GET    /stores(.:format)                                    stores#index
                           store GET    /stores/:id(.:format)                                stores#show
      

      locations 的收集操作,例如。 index,嵌套在stores 下,因为locations 属于stores,但是要识别特定位置,路由引用locations/1 不带stores/ 前缀,因为您不需要store标识location 的ID。

      这会沿着树向下级联:要识别 business_hours 收集操作,您需要时间所属的 location,但是因为您有一个 location ID,所以您不需要涉及 store,所以你得到locations/:id/business_hours。当您需要特定的时间时,您不再需要 location,因此您只需获得 /business_hours/1。

      如果您想维护小时收集路径的整个层次结构(即/stores/1/location/2/business_hours),您需要不使用shallow 您的locations 路径,这将保留其成员操作(show, edit 等)在 /stores/1/locations/2 下,或者您需要使用较少的 Rails 帮助程序手动指定您想要的路径。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-11
        • 1970-01-01
        • 2015-01-19
        相关资源
        最近更新 更多