rails结构化嵌套资源的路由/控制器/视图
我有以下结构的rails应用程序:
user has_many posts
post has_many post_comments
post_comment has_many comment_replies
我打算使用以下路线来避免深度嵌套。
resources :posts do resources :post_comments, module: :posts end resources :comments do resources :comment_replies, module: :post_comments #is this module a good choice? end
这给出了以下控制器结构
post_comments GET /posts/:post_id/comments(.:format) posts/comments#index POST /posts/:post_id/comments(.:format) posts/comments#create new_post_comment GET /posts/:post_id/comments/new(.:format) posts/comments#new edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) posts/comments#edit post_comment GET /posts/:post_id/comments/:id(.:format) posts/comments#show PATCH /posts/:post_id/comments/:id(.:format) posts/comments#update PUT /posts/:post_id/comments/:id(.:format) posts/comments#update DELETE /posts/:post_id/comments/:id(.:format) posts/comments#destroy comment_repiles GET /comments/:comment_id/repiles(.:format) comments/repiles#index POST /comments/:comment_id/repiles(.:format) comments/repiles#create new_comment_repile GET /comments/:comment_id/repiles/new(.:format) comments/repiles#new edit_comment_repile GET /comments/:comment_id/repiles/:id/edit(.:format) comments/repiles#edit comment_repile GET /comments/:comment_id/repiles/:id(.:format) comments/repiles#show PATCH /comments/:comment_id/repiles/:id(.:format) comments/repiles#update PUT /comments/:comment_id/repiles/:id(.:format) comments/repiles#update DELETE /comments/:comment_id/repiles/:id(.:format) comments/repiles#destroy
我的问题是篡改文件夹。
对于控制器:这意味着我将posts_controller
放在主文件夹中, posts_controller
进入posts
文件夹。 到目前为止,它很清楚。 但是对于comment_replies
我应该将它放在comment_replies
文件夹中,该文件夹与找到post_comments_controller
地方完全分开。
对于视图:我有一个create.js.erb
用于’post’文件夹中的post。 我在posts/post_comments
文件夹中有一个create.js.erb
。 根据我的路线,我应该将comment_replies
的create.js.erb
放入create.js.erb
post_comments/comment_replies folder
。 但这似乎与控制器示例一样反直觉。
在这种情况下,rails约定/常见解决方案是什么? 顺便说一句。 我不想在他们的post中单独显示评论或回复。
UPDATE
posts_controller
def index .... @post_comments = @post.post_comments #showing all comments @post_comment = PostComment.new #new comment via js respond_to do |format| format.js end end
post_comments控制器
def create @post = Post.find(params[:id]) @post_comment = @post.post_comments.build(post_comment_params) @post_comment.save! end