Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Routes: Namespace with more params

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.

like image 477
Maikel Urlitzki Avatar asked Nov 13 '12 14:11

Maikel Urlitzki


2 Answers

You can use scope.

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

You will get those routes below:

$ 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

like image 84
hiroshi Avatar answered Nov 04 '22 12:11

hiroshi


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.

like image 33
mrbrdo Avatar answered Nov 04 '22 10:11

mrbrdo