【问题标题】:Scoping resource routes in Rails 4Rails 4 中的资源路由范围
【发布时间】:2014-09-25 15:55:15
【问题描述】:

我有一个resources :shops

导致/shops/shops/:id

我知道我可以在集合或成员范围内使用

resources :shops do
  scope ":city" do
   # collection and members
  end
end

或者在之前使用

scope ":city" do
 resources :shops
end

但我不知道如何让路由出现在所有成员(包括标准 REST 成员)和集合上,就像这样

/shops/:city/

/shops/:city/:id

【问题讨论】:

  • 您想要/shops/:city/:id 等路由?
  • 是的,所以每次使用商店路线时,它总是有一个 :city 范围
  • 似乎不标准。你能解释一下你的用例吗?
  • 我不介意改变周围的东西。基本上,我有一堆具有城市属性的商店。我想只在某个城市范围内的商店,并将其反映在一条路线中。因此,如果使用friendly_id、/shops/new-york/joes-dinner 和/shops/los-angeles/joes-dinner 将导致不同的商店页面。如果需要,我不介意创建城市模型

标签: ruby-on-rails ruby-on-rails-4 routes scope


【解决方案1】:

根据您的use case 和问题,您正在尝试使用逻辑错误的路线。您在城市内有商店,而不是在商店内有城市。

首先你应该规范你的数据库。您应该创建另一个表 cities 并将 city 属性替换为 shops 表中的 city_id

您需要在citiesshops 之间关联has_manybelongs_to

# Models
class City < ActiveRecord::Base
  has_many :shops
  ... # other stuff
end

class Shop < ActiveRecord::Base
  belongs_to :city
  ... # other stuff
end

路线

resources :cities do
  resources :shops
end

它将生成如下路线:

               POST     /cities/:city_id/shops(.:format)          shops#create
new_city_shop  GET      /cities/:city_id/shops/new(.:format)      shops#new
edit_city_shop GET      /cities/:city_id/shops/:id/edit(.:format) shops#edit
    city_shop  GET      /cities/:city_id/shops/:id(.:format)      shops#show
               PATCH    /cities/:city_id/shops/:id(.:format)      shops#update
               PUT      /cities/:city_id/shops/:id(.:format)      shops#update
               DELETE   /cities/:city_id/shops/:id(.:format)      shops#destroy

从逻辑上讲,这些路线将显示特定商店所在的城市。

【讨论】:

  • 好像没问题,有没有办法去掉 /cities/ 前缀?
  • 为什么要这样做?我宁愿不这样做..这是我们休息路线的方式..出于安全原因,您可以使用friendly_id修改您的id
【解决方案2】:

命名空间

您不妨考虑添加namespace

由于您尝试为商店拉出cities(即我想您想在Sao Paulo 中显示商店),您可以这样做:

#config/routes.rb
namespace :shops do
   resources :cities, path: "", as: :city, only: [:index] do #-> domain.com/shops/:id/
      resources :shops, path: "", only: [:show] #-> domain.com/shops/:city_id/:id
   end
end

这将允许您创建一个单独的控制器:

#app/controllers/shops/cities_controller.rb
Class Shops::CitiesController < ApplicationController
   def index
      @city = City.find params[:id]
   end
end

#app/controllers/shops/shops_controller.rb
Class Shops::ShopsController < ApplicationController
   def show
      @city = City.find params[:city_id]
      @shop = @city.shops.find params[:id]
   end
end

这将确保您能够创建所需的路由结构。命名空间做了两件重要的事情——

  1. 确保您拥有正确的路由结构
  2. 分离你的控制器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2011-09-19
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    相关资源
    最近更新 更多