Ruby on Rails Routes: Namespace with more params

namespaces, routes, ruby, ruby-on-rails

Solution

If you have those nike, adidas etc. in the database then the most straightforward option is to use match.

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

However it seems to me that shop should be a resource for you. Just create a ShopsController (you don't need a matching model for it, just a controller). Then you can do

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

Now you can access the news index page (/shop/adidas) like this:

shop_path("adidas")

In the NewsController use `:shop_id` to access the name of the shop (yes even though it's _id it can be a string). Depending on your setup you may want news to be a singular resource, or the news method to be a collection method.

Also are you sure just renaming the news resource isn't something you want?

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

Keep in mind also that controller names and the number of controllers need not match your models. For example you can have a News model without a NewsController and a ShopsController without a Shop model. You might even consider adding a Shop model to your database if that makes sense. In case this is not your setup then you might have oversimplified your example and you should provide a more full description of your setup.

Problem

i have a namespace "shop". In that namespace i have a resource "news". ``` namespace :shop do resources :news end ``` What i now need, is that my "news" route can get a new parameter: ``` /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 ``` So that i can get the shop and filter my news. I need a route like: ``` /shop/:identfier/:controller/:action/:id ``` I tested many variations but i cant get it running. Anyone can get me a hint? Thanks.

Original source