在Rails 3.x中,如何为引用父资源的嵌套资源设计视图?

假设我有一个嵌套资源,如Rails指南示例: http : //guides.rubyonrails.org/routing.html#nested-resources

resources :magazines do resources :ads end 

这会将对/ magazine / newsweek / ads的调用路由到AdsController#index。 它需要URL中的magazine_id …我应该如何创建基于用于Ads#index的模板的视图,还包括父资源的上下文?

例如,拥有广告的所有父资源都会包含这些广告的表格列表。 但我希望视图的顶部包含每个杂志的样板信息。 如果/ magazines / newsweek / ads直接转到通用的AdsController#index,如何让#index视图意识到需要包含从Magazine模型生成的样板?

如果其他模型与广告有关系(TelevisionShow has_many:ads),我希望AdsController #index对这些也有不同的反应。

编辑:

这就是我过去通过MagazinesController完成这些事情的方式。 假设我想要一个单独的杂志#show action …路线将是:

 resources :magazines resources :ads get "magazines/:id/ads", :controller=>"companies", :action=>"ads" 

控制器将是:

 class MagazinesController < ApplicationController def show ... end def ads ... end end 

然后,杂志#广告将部分用于广告列表,这些广告列表将在所有其他类型的资源中共享。

对我来说很有意义,但那条路似乎可能会以某种方式干掉?

听起来你应该在杂志控制器中工作。

 #Magazine_controller def show @magazine = Magazine.find(params[:id]) @ads = @magazine.ads end 

然后在您的视图中,只为您的广告集合渲染部分内容。 您的广告部分将保存在广告区域中。 所以在你看来:

 <%= render :partial => "ads/ad", :collection => @ads %> 

http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials