问题
I have rails app with the following structure:
user has_many posts
post has_many post_comments
post_comment has_many comment_replies
I'm planning to use the following routes to avoid deep nesting.
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
This gives the following controller structure
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
My problem is with sturcturing the folders.
For controllers: It means I put the posts_controller
in the main folder and the post_comments_controller
goes into posts
folder. Until now it's clear. But for comment_replies
I should put it in the comment_replies
folder which is totally separated from where post_comments_controller
can be found.
For views: I have a create.js.erb
for posts
in the 'post' folder. I have a create.js.erb
for post_comment
in the posts/post_comments
folder. According to my routes I should put the create.js.erb
for comment_replies
into the post_comments/comment_replies folder
. But this seems to be counterintuitive again just like the controller example.
What is the rails convention/ common solution in this case? Btw. I don't wanna show comments or replies separately from their 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 controller
def create
@post = Post.find(params[:id])
@post_comment = @post.post_comments.build(post_comment_params)
@post_comment.save!
end
来源:https://stackoverflow.com/questions/35672666/rails-structuring-routes-controller-views-for-nested-resources