我有以下型号:
- 发布
- 标签
- TaggedPost(Post和Tag通过has_many:through从中派生它们的关联)
我有以下routes.rb文件:
resources :tags resources :posts do resources :tags end因此,当我导航到/posts/4/tags时,这将带我进入参数数组中设置了post_id值的Tag控制器的索引动作.很好.
So when I navigate to, say, /posts/4/tags, that will shoot me into the index action for the Tag controller with the post_id value set in the parameters array. Cool.
但是,我的问题是,既然我正在访问帖子下的嵌套标签资源,是否应该仍然点击标签"控制器?还是应该设置其他控制器来处理标签的嵌套性质?否则,我必须在标记"控制器中构建其他逻辑.当然可以做到这一点,但这是处理嵌套路由和资源的常用方法吗?我在标记"控制器的索引操作中具有的代码如下:
My question is though, now that I'm accessing the nested tags resource under posts, should I be hitting the Tags controller still? Or should I setup some other controller to handle the nested nature of tags at this point? Otherwise I have to build additional logic into the Tags controller. This can be done of course, but is this the common way of handling nested routes and resources? The code I have in the index action for the Tags controller is as follows:
TagsController.rb
def index if params[:post_id] && @post = Post.find_by_id(params[:post_id]) @tags = Post.find_by_id(params[:post_id]).tags else @tags = Tag.order(:name) end respond_to do |format| format.html format.json {render json: @tags.tokens(params[:q]) } end end随着我计划将许多其他资源与标记资源相关联,我可以看到该控制器中的代码越来越大.关于如何实现这一点的想法?
I can see the code in this controller growing increasingly large, as I plan for many additional resources to be associated with tag resources. Thoughts on how to break this out?
问题摘要:
让我知道是否需要更多信息.
Let me know if you need more information.
推荐答案您对嵌套资源所做的所有工作都是在更改路由URL.您只需要做的就是确保将正确的ID(在您的情况下为准)传递给标签控制器.最常见的错误是找不到*** ID.
All you are doing with nested resources is changing the routing URL. Only thing you would have to do is make sure you are passing the proper id (in your case post)to the tag controller. Most common error is the Can't Find *** ID.
如果您没有将个人资料路由嵌套到用户路由中,则看起来像这样
If you don't nest a profile route into a user route it would look like this
domain/user/1
domain/user/1
domain/profile/2
domain/profile/2
嵌套路线时将是
domain/user/1/profile/2
domain/user/1/profile/2
这就是它所做的一切,仅此而已. 您不需要其他控制器.进行嵌套路由只是为了外观.允许您的用户关注关联.关于嵌套路由,最重要的是要确保将link_to设置为正确的路径.
That is all that it is doing and nothing else. You don't need additional controllers. Doing nested routing is just for looks. allowing your user to follow the association. The most important thing about nesting routes is that you make sure you make the link_to's to the right path.
不嵌套时:
user_path和
profile_path当它嵌套时,您将需要使用
when it is nested you would need to use
user_profile_pathrake routes是您的朋友,以了解路线的变化方式.
rake routes is your friend to find out how the routes have changed.
希望有帮助.
更多推荐
Rails嵌套资源和路由
发布评论