我相信我们都熟悉要显示的正常帖子和评论模型。现在想象一下那些关系。我想在我的评论中添加replies
,因此我们的路由如下
resources :posts do
resources :comments do
resources :replies do
end
end
我在观点中尝试了很多不同的实现方法,但我没有运气!当我的实际控制器为post
并且我想访问replies
时,它就无效。我试着搜索这个,但没找到合适的名字。是否有任何资源有关于如何实现此系统的信息或有关如何使其在n级而不是2级上工作的代码片段?
答案 0 :(得分:1)
经验法则:
资源不应该嵌套超过1级。
我建议你阅读Jamis Buck的this article。你可能想做类似的事情:
resources :posts do
resources :comments
end
resources :comments
resources :replies
end
答案 1 :(得分:1)
http://nithinbekal.com/posts/rails-shallow-nesting/
您可以使用浅嵌套。
resources :posts, shallow: true do
resources :comments do
resources :replies do
end
end
这样,当您需要创建嵌套对象 [new and create action] 或查看所有相关对象 [索引视图] 时,您只有一个嵌套路径。看看下面的前三行,看看我的意思。然后你就拥有了不需要知道这种关系的资源的正常路线。
comment_replies GET /comments/:comment_id/replies(.:format) replies#index
POST /comments/:comment_id/replies(.:format) replies#create
new_comment_reply GET /comments/:comment_id/replies/new(.:format) replies#new
edit_reply GET /replies/:id/edit(.:format) replies#edit
reply GET /replies/:id(.:format) replies#show
PATCH /replies/:id(.:format) replies#update
PUT /replies/:id(.:format) replies#update
DELETE /replies/:id(.:format) replies#destroy
post_comments GET /posts/:post_id/comments(.:format) comments#index
POST /posts/:post_id/comments(.:format) comments#create
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
edit_comment GET /comments/:id/edit(.:format) comments#edit
comment GET /comments/:id(.:format) comments#show
PATCH /comments/:id(.:format) comments#update
PUT /comments/:id(.:format) comments#update
DELETE /comments/:id(.:format) comments#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format)