问题
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
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?
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?
And if other models have relationships to ads (TelevisionShow has_many :ads), I'd like AdsController#index to react differently to those as well.
EDIT:
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"
And the controller would be:
class MagazinesController < ApplicationController
def show
...
end
def ads
...
end
end
And then Magazine#ads would have a partial for ads listings that would be shared across all other types of resources.
Makes sense to me, but that route seems like it could somehow be DRYer?
回答1:
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
来源:https://stackoverflow.com/questions/7109201/in-rails-3-x-how-to-design-a-view-for-a-nested-resource-that-refers-to-the-pare