post has_many comments
のアソシエーション。
postに紐づくcommentを全て削除するとき、理想ならこんな感じのエンドポイントにしたい↓
DELETE /posts/:post_id/comments
が、デフォルトのresourcesではこのようなエンドポイントを作るのは無理なので、以下のようにする。
1
2
3
4
5
6
7
|
resources :posts do
resources :comments, only: [] do # resourcesで自動生成されるアクションが全て不要なときはこのようにonlyを記述する
collection do
delete '', action: :destroy_all
end
end
end
|
これで、DELETE /posts/:post_id/comments
リクエストがcomments#destroy_all
アクションに行くようになる。
ヘルパーはpost_comments_path
コントローラはこんな感じ↓
1
2
3
4
5
6
7
|
class CommentsController < ApplicationController
def destroy_all
@post = Post.find(params[:post_id])
@post.comments.destroy_all
redirect_to post_path(@post)
end
end
|
参考
Railsで一度に全部処理するときのRoutes問題 - blog.takuyan.com