掲示板のコメント機能を実装してみた
今回は、掲示板にコメントをする機能を実装してみた。 railsチュートリアルの総復習といった感じで、色々なエラーにぶち当たるも何とか実装終了。 学んだことを記します。
・URLをネストさせるためには、routingを下のように記載する
resources :boards do resources :comments end
これにより、下のようなルーティングが作成される
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)
しかし、このURLはいささか冗長すぎる。例えば特定のコメントを表示させたい場合、コメントは一意性を持っておりIDが被ることはあり得ない。
そのため/comment/:id
だけがあればよく、手前の/boards/:board_id
は不要である。
そこで、shallowオプションを使ってURLを簡略化することができる。
resources :boards do resources :comments, shallow: true end
生成されるURL
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)
・form_withに渡すURLの表記方法
通常は下の書き方
url: board_comment_path(board, comment)
しかし、これを下のように書くこともできる
url:[board, comment]
ただ、如何せん初学者のため、ターミナルでroutingをしっかりと調べてpath形式で書いた方がわかりやすい気がする。。。
「慣れてきたらこういう書き方をして、コードを簡略化してね」ということだろう。
・リソース判定の記載場所
リソース判定は、viewファイルではなくモデルファイルの中に記載しておくことで、後から一括変更を加える時に非常に楽になる。 また、1つのモデルファイルに全てまとめてあるとなおよい。
自分の実装方法(Viewファイルに記載する場合)
if current_user.id == comment.user_id
推奨される実装方法(Userモデルに記載)
def my_comment?(comment) comment.user_id == self.id の省略形 end
そして、viewファイルには下のように記載する
if current_user.my_comment?(@comment)
・ifとelseのredirect先が同じ場合、まとめて記載することができる
今までの記載方法
if @comment.save flash[:success] = … redirect_to board_path(@board.id) else flash[:danger] = … redirect_to board_path(@board.id) end end
まとめた後
if @comment.save flash[:success] =… else flash[:danger] = … end redirect_to board_path(@board.id) end
・エラーの解決方法
Missing templateエラー(パーシャルが読み込めないよ〜と言われた)
・Missing partial comments/_comment with {:locale=>[:ja], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}. Searched in: * "/Users/test/552_yukimura907_runteq_learning_basic/app/views"
_comment.html.erbをboards
ディレクトリに作ってしまっていたのが原因。
_comment.html.erb
のファイルをboardsディレクトリからcommentsディレクトリに移動することで解決