【问题标题】:Ruby on Rails Routes: Namespace with more paramsRuby on Rails 路由:具有更多参数的命名空间
【发布时间】:2012-11-02 00:02:56
【问题描述】:

我有一个命名空间“商店”。在那个命名空间中,我有一个资源“新闻”。

namespace :shop do
  resources :news  
end

我现在需要的是,我的“新闻”路由可以得到一个新参数:

/shop/nike (landing page -> goes to "news#index", :identifier => "nike")
/shop/adidas (landing page -> goes to "news#index", :identifier => "adidas")
/shop/nike/news
/shop/adidas/news

这样我就可以获取商店并过滤我的新闻。

我需要这样的路线:

/shop/:identfier/:controller/:action/:id

我测试了许多变体,但无法运行。

谁能给我一个提示?谢谢。

【问题讨论】:

  • 您事先知道这些页面的名称还是需要从数据库中生成它们?

标签: ruby-on-rails ruby namespaces routes


【解决方案1】:

如果你的数据库中有耐克、阿迪达斯等,那么最直接的选择就是使用匹配。

namespace :shop
  match "/:shop_name" => "news#index"
  match "/:shop_name/news" => "news#news"
end

但在我看来,商店应该是您的资源。只需创建一个 ShopsController(您不需要匹配的模型,只需一个控制器)。然后就可以了

resources :shops, :path => "/shop"
  resources :news
end

现在您可以像这样访问新闻索引页面 (/shop/adidas):

shop_path("adidas")

在 NewsController 中使用:shop_id 来访问商店的名称(是的,即使它是_id,它也可以是一个字符串)。根据您的设置,您可能希望 news 是一个单一的资源,或者 news 方法是一个集合方法。

您还确定只是重命名新闻资源不是您想要的吗?

resources :news, :path => "/shop" do
  get "news"
end

还要记住,控制器名称和控制器数量不必与您的型号匹配。例如,您可以有一个没有 NewsController 的 News 模型和一个没有 Shop 模型的 ShopsController。如果有意义的话,您甚至可以考虑将 Shop 模型添加到您的数据库中。 如果这不是您的设置,那么您可能过于简化了您的示例,您应该提供更完整的设置描述。

【讨论】:

    【解决方案2】:

    您可以使用scope

    scope "/shops/:identifier", :as => "shop" do
      resources :news
    end
    

    您将获得以下路线:

    $ rake routes
    shop_news_index GET    /shops/:identifier/news(.:format)          news#index
                    POST   /shops/:identifier/news(.:format)          news#create
      new_shop_news GET    /shops/:identifier/news/new(.:format)      news#new
     edit_shop_news GET    /shops/:identifier/news/:id/edit(.:format) news#edit
          shop_news GET    /shops/:identifier/news/:id(.:format)      news#show
                    PUT    /shops/:identifier/news/:id(.:format)      news#update
                    DELETE /shops/:identifier/news/:id(.:format)      news#destroy
    

    http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多