Rails: Resource reachable from two routes, or better approach?

淺唱寂寞╮ 提交于 2019-12-24 03:29:55

问题


I'm working on an app where users can share photos. The photos can optionally belong to a collection, but don't have to.

Currently users can look through all photos via: photos/id. I think it would also make sense if they could browse through the photos for a particular collection through collections/id/photos

So, this would mean that photos were both a top level resource and a nested resource. I suppose I could set this up in the routes like so:

resources :photos
resources :collections do
  resources :photos
end

Is this a good idea, or is there a better way to reuse the photo model while also allowing it to act as nested under collections when appropriate? I'd very much appreciate suggestions as to the "rails way" of handling this kind of scenario.

Thanks!


回答1:


The routes you've suggested work perfectly fine. You do need to watch out in your Photos controller actions, though. Because they can be called for an individual photo OR a collection, you need to conditionally find photos based on what params are available.

Also, I'd suggest being more specific about which actions are available for each route:

resources :photos
resources :collections do
  resources :photos, :only => [:index, :create, :destroy]
end

# index => show photos in a collection
# create => add a photo to a collection
# destroy => remove a photo from a collection

You don't really need to be able to edit/update/show a photo as a member of a collection from the information you provided.

Another option is to use a namespaced route:

namespace :collection, :path => '/collection', :as => :collection do
  resources :photos, :only => [:index, :create, :destroy]
end

That will allow you to separate your Collection::Photos from your Photos…

controllers/photos_controller.rb
controllers/collections/photos_controller.rb

And if you really want, Rails lets you do the same to your views. Another benefit of using the namespace is that it sets up some really nifty route helpers:

photo_path(@photo) #=> /photos/1
collection_photos_path #=> /collections/1/photos
etc.


来源:https://stackoverflow.com/questions/5148921/rails-resource-reachable-from-two-routes-or-better-approach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!