Rails:可以从两条路线获得资源,还是更好的方法? [英] Rails: Resource reachable from two routes, or better approach?

查看:72
本文介绍了Rails:可以从两条路线获得资源,还是更好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个用户可以共享照片的应用程序。这些照片可以选择属于某个收藏集,但不一定要属于这些照片。

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

当前用户可以通过以下方式浏览所有照片: photos / id 。我认为如果他们能够通过 collections / id / photos

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.

谢谢!

推荐答案

您建议的路线非常合适。不过,您确实需要注意照片控制器的操作。由于可以将它们称为单张照片或收藏集,因此您需要根据可用的参数有条件地查找照片。

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

如果您确实想要,Rails可以对您的视图执行相同的操作。使用命名空间的另一个好处是它设置了一些非常漂亮的路由助手:

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.

这篇关于Rails:可以从两条路线获得资源,还是更好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆