我有以下型号:
- 发布
- 标签
- TaggedPost(通过 has_many :through 从中导出 Post 和 Tag 的关联)
我有以下 routes.rb 文件:
resources :tags resources :posts do resources :tags end因此,当我导航到 /posts/4/tags 时,这将使我进入标签控制器的索引操作,其中设置了 post_id 值参数数组.很酷.
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嵌套时,您需要使用
user_profile_pathrake routes 是您了解路由变化的朋友.
rake routes is your friend to find out how the routes have changed.
希望有帮助.
更多推荐
Rails 嵌套资源和路由
发布评论