LoginSignup
1
0

More than 1 year has passed since last update.

【Rails】コメント機能のparamsにmergeの意味を調べた

Posted at

コメント機能の実装する際に、comments_controllerにて以下の記述を行なった。

comments_controller.rb
class CommentsController < ApplicationController

  def create
    comment = current_user.comments.new(comment_params)

    if comment.save
      redirect_to board_path(comment.board),success: t('.success', item: Comment.model_name.human) 
    else
      redirect_to board_path(comment.board),danger: t('.fail', item: Comment.model_name.human)
    end
  end

  def destroy
    comment = current_user.comments.find_by(id: params[:id])

    if comment.destroy
      redirect_to board_path(comment.board)
    end
  end

  private

  def comment_params
    params.require(:comment).permit(:body).merge(board_id: params[:board_id])
  end
end

上記内のmerge(board_id: params[:board_id])がよく分からなかったので、調べてみた。

paramsのらいlsガイドを参照すると

ルーティングで定義されるその他の値パラメータ (id など) にもアクセスできます。

つまりURLからも中身を持って来れることが分かった。
もう少し細かく見てみる。

paramsメソッドで、ルーティングで定義されたboard_idを取得する

コメント機能は、User、Boardと関連しているので、user-id と board-id が必須。

なので、フォームから comment[:body]を取得しつつ、board_id がいる。

board_id はルーティングで url 内に下記のように含まれている。

boards/:board_id/comments

これは、ルーティングで

  resources :boards do
    resources :comments, shallow: true
  end

と指定しているからparams で board_id を取得できる。

参考記事

paramsメソッドはルーティングパラメータとpostデータを取得できる【25/30 2nd】

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0