0

Let's take a look at nested resource example, the following is the model:

class Magazine < ActiveRecord::Base
  has_many :ads, :order => 'time_start'
end

class Ad < ActiveRecord::Base
  belongs_to :magazine
end

and the routing so far looks like this:

resources :magazines do
  resources :ads
end

this automatically yields URLs like /magazines/:magazine_id/ads/:id.

However, I'd like to have slightly different URLs scheme, much more "magazine"-centric. General nested URL scheme should look like that: /magazines/:id/:ad_num/component, where:

  • ":id" is what was ":magazine_id" in standard generated routing URLs, a primary key for magazine object in database
  • ":ad_num" is a way to identify a single ad inside a given magazine, but it's not a database identifier, but instead an index in array of ads in a single magazine
  • There should be no generic "show" action (i.e. /magazines/:id/:ad_num), but instead there are multiple components inside an "ad", which are shown using several different actions

I'd like to have no AdsController at all, all these routes should point to various actions in MagazineController instead, for example magazines/5/1/title should point to MagazineController => title with params[:id] = 5 and params[:ad_num] = 1.

Of course, a useful URL helper like title_ad_magazine(@magazine, @ad) would be most helpful.

How do I do that in new Rails routing DSL?

4

1 回答 1

1

您可以像这样使用这些参数键生成自定义路由

 get '/magazines/:id/:ad_num/title' => 'magazine#title', as: :magazine_ads_title

您将拥有parmams[:id]params[:ad_num]匹配 url 的这些部分

您不需要使用 as: 选项,但您可能会发现生成我直观的 url 帮助程序很有帮助

于 2013-10-24T09:44:59.113 回答