1
1

Rails: パーシャルに渡す変数は、なるべく少ない方がいいというレビューを受けた話(haml記法)

Last updated at Posted at 2024-07-04

読んで欲しい人

  • モデルにアソシエーションがあるのに、パーシャルに渡す変数を複数個にしてる方へ
  • 過去の自分

動作環境

  • ruby 3.3.0
  • Rails 7.1.3.3

前提

作っているもの

  • ポスト詳細画面に表示する、コメント一覧のパーシャル

レビュー内容とコード

レビュー内容

-    = render 'posts/comments', comments: @comments, post: @post
+    = render 'posts/comments', comments: @comments

コメント

  • モデル同士がお互いを知っているのであれば、渡す変数は1つの方がいい

コード構成と内容

モデル:postとcommentは、1対多の関係性

post.rb
has_many :posts, dependent: :destroy
comment.rb
belongs_to :post

コントローラ

posts_controller.rb
def show
  @post = Post.find(params[:id])
  # コメントを一覧を表示するためのインスタンス変数
  @comments = @post.comments.comments_order
end

ビュー

# posts/show.html.hamlファイル

.post-container
  = @post.user.name
  = @post.user.content
.comment-container
-  = render 'posts/comments', comments: @comments, post: @post
+  = render 'posts/comments', comments: @comments

パーシャルビュー

# posts/show.html.hamlファイル

%ul.list-group
  - comments.each do |comment|
    %li.list-group-item
      .comment
        = comment.content
        .d-flex
-          = link_to '編集', edit_post_comment_path(post, comment)
-          = button_to '削除', post_comment_path(post, comment)
+          = link_to '編集', edit_post_comment_path(comment.post, comment)
+          = button_to '削除', post_comment_path(comment.post, comment)

パーシャルに渡す変数を少なくした方がいい理由

  • パーシャルだけをパッと見た時に、postとcommetnsは関連性がないのかな?と思ってしまう
  • インスタンス変数を変えたいとなった時に、シンプルに変える箇所が多くなる、保守性が低め
  • コードが短くなる

感想、学んだこと

  • コードを他の人が見たときに、どう思うのか?という視点が学べた
  • 自分がどのモデルと紐づいているのかは、データ同士(今回の場合はpostとcomment)が一番知っている
  • 関連が頭に入っていればこの間違えはなかったなぁ

以上

1
1
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
1