コメント機能の実装
掲示板にユーザーがコメントできるようにする
Commentモデルの作成及びアソシエーションの確認
コメントは掲示板に属して、ユーザーに属するので、
bundle exec rails g model Comment body:text user:references board:references
を実行、Userモデルは複数のCommentモデルを持ち、boardモデルも複数のCommentモデルを持ち、Commentモデルのbodyカラムは最長65535文字まで、また、ユーザーや掲示板が削除された時、関連付けたコメントを削除できるように
#user.rb has_many :comments, dependent: :destroy #board.rb has_many :comments, dependent: :destroy #comment.rb validates :body, presence: true, length: { maximum: 655_35 }
をそれぞれ追記 また、ルーティングについて今回1つの掲示板に対して、複数のコメントがあり、その1つ1つに特定のURLを振り分けるとする。このようにリソースの配下に他のリソースを配置するにはルーティングをネストすることで、この親子関係をルーティングで表現できる。今回の場合は以下のように宣言する
#routes.rb resources :boards do resources :comments end
bundle exec rails routesで確認すると
board_comments GET /boards/:board_id/comments(.:format) comments#index POST /boards/:board_id/comments(.:format) comments#create new_board_comment GET /boards/:board_id/comments/new(.:format) comments#new edit_board_comment GET /boards/:board_id/comments/:id/edit(.:format) comments#edit board_comment GET /boards/:board_id/comments/:id(.:format) comments#show PATCH /boards/:board_id/comments/:id(.:format) comments#update PUT /boards/:board_id/comments/:id(.:format) comments#update DELETE /boards/:board_id/comments/:id(.:format) comments#destroy
のようにboardsリソースにcommentリソースがネストされたルーティング生成できる また、commentコントローラのshow,edit,update,destroyアクションについてはboardsリソースは必要ない、こんな時に使われるのがshallowオプション、本来なら
resources :boards do resources :comments, only: %i[index new create] end resources :comments, only: %[show edit update destroy]
と記述することでこの4つのアクションだけはcommemnts/:idのようにboardsリソースをネストしないようにできるが、shallowオプションでこれを
resources :boards do resources :comments, shallow: true end
と簡潔に記述できる bundle exec rails routesで確認すると
board_comments GET /boards/:board_id/comments(.:format) comments#index POST /boards/:board_id/comments(.:format) comments#create new_board_comment GET /boards/:board_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
とindex,create,newアクションだけboardsリソースにネストされたルーティングが生成できる!!
参考文献