本文介绍了在Rails 3.x中,如何为引用父资源的嵌套资源设计视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a nested resource like in the Rails guide example:http://guides.rubyonrails.org/routing.html#nested-resources

resources :magazines do
  resources :ads
end

这会将呼叫/magazines/newsweek/ads路由到AdsController#index.网址中需要有一个magazine_id ...我该如何基于基于Ads#index的模板创建视图,但还要包含父资源的上下文?

This routes a call to /magazines/newsweek/ads to the AdsController#index. It requires a magazine_id in the URL...how should I go about creating a view that is based off of a template used for Ads#index yet also includes the context of the parent resource?

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

For example, all parent resources that have Ads will have a table list of those ads. But I'd like the top of the view to include boilerplate information for each Magazine. If /magazines/newsweek/ads goes directly to the generic AdsController#index, how do I make that #index view aware of the need to include boilerplate generated from the Magazine model?

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

And if other models have relationships to ads (TelevisionShow has_many :ads), I'd like AdsController#index to react differently to those as well.

这是我过去通过MagazinesController做这些事情的方式.假设我想要一个单独的Magazine#show动作...路线将是:

This is how I've done such things in the past, going through MagazinesController. Let's say I want a separate Magazine#show action...the routes would be:

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

控制器将是:

class MagazinesController < ApplicationController
  def show
    ...
  end

  def ads
    ...
  end

end

然后Magazine#ads将部分广告列表与所有其他类型的资源共享.

And then Magazine#ads would have a partial for ads listings that would be shared across all other types of resources.

对我来说很有道理,但是那条路线似乎可以用DRYer吗?

Makes sense to me, but that route seems like it could somehow be DRYer?

推荐答案

听起来您应该在弹匣控制器中工作.

It sounds like you should be working in the magazine controller.

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

然后在您的视图中仅呈现广告集合的部分内容.您的部分广告将保存在广告区域中.因此,根据您的意愿:

Then in your view just render a partial for your collection of ads. Your ads partial will be saved in the ads area. So in your veiw:

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

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

这篇关于在Rails 3.x中,如何为引用父资源的嵌套资源设计视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 08:49