Mai*_*zki 5 ruby routes namespaces ruby-on-rails
我有一个名称空间"shop".在该命名空间中,我有一个资源"新闻".
namespace :shop do
resources :news
end
Run Code Online (Sandbox Code Playgroud)
我现在需要的是,我的"新闻"路线可以获得一个新参数:
/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
Run Code Online (Sandbox Code Playgroud)
所以我可以得到商店并过滤我的新闻.
我需要一条路线:
/shop/:identfier/:controller/:action/:id
Run Code Online (Sandbox Code Playgroud)
我测试了很多变化,但我不能让它运行.
任何人都可以给我一个提示?谢谢.
hir*_*shi 11
您可以使用scope.
scope "/shops/:identifier", :as => "shop" do
resources :news
end
Run Code Online (Sandbox Code Playgroud)
您将在下面获得这些路线:
$ 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
Run Code Online (Sandbox Code Playgroud)
http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing
如果数据库中有耐克、阿迪达斯等产品,那么最直接的选择就是使用匹配。
namespace :shop
match "/:shop_name" => "news#index"
match "/:shop_name/news" => "news#news"
end
Run Code Online (Sandbox Code Playgroud)
然而在我看来,商店应该是你的一种资源。只需创建一个 ShopsController(您不需要为其匹配模型,只需要一个控制器)。然后你可以做
resources :shops, :path => "/shop"
resources :news
end
Run Code Online (Sandbox Code Playgroud)
现在您可以像这样访问新闻索引页面(/shop/adidas):
shop_path("adidas")
Run Code Online (Sandbox Code Playgroud)
在 NewsController 中用于:shop_id访问商店的名称(是的,即使它是 _id,它也可以是一个字符串)。根据您的设置,您可能希望新闻成为单一资源,或者新闻方法成为收集方法。
另外,您确定仅仅重命名新闻资源不是您想要的吗?
resources :news, :path => "/shop" do
get "news"
end
Run Code Online (Sandbox Code Playgroud)
另请记住,控制器名称和控制器数量不必与您的型号相匹配。例如,您可以拥有一个没有 NewsController 的 News 模型和一个没有 Shop 模型的 ShopsController。如果有意义的话,您甚至可以考虑将 Shop 模型添加到数据库中。如果这不是您的设置,那么您可能过于简化了示例,您应该提供更完整的设置描述。
| 归档时间: |
|
| 查看次数: |
5280 次 |
| 最近记录: |