はじめに
掲示板アプリを作成しているのだが、
いいね機能実装時、
を参考に(ほぼ写して)、コードを書いていた。
機能自体の実装は成功したが、ビューでの表示が思うようにいかない。
各投稿一つ一つに、全ての投稿のイイねボタンがついてしまった。
これに対処するにあたって、
今までおざなりにしていた、renderとそのオプションについての理解がかなり深まったので、備忘録として残す。
バージョンなど
ruby 2.5.1
rails 5.2.4.1
bootstrap 4.4.1
haml-rails 2.0.1
jquery-rails 4.3.5
コード
posts_controller.rb
def index
@posts = Post.all.includes(:user).order('created_at DESC')
end
index.html.haml
.events__wrapper.row
/# each文
- @posts.each do |post|
.events__content.col-sm-6.col-md-3.mb-3
.card{id: post.id}
%label.m-1
- if post.image
%img.card-img-top{src: "#{post.image}"}
- else
%img.card-img-top{src: "/public/noimage.jpeg"}
.card-body.event
%h5= link_to "#{post.title}", post_path(post.id), class: "event-title stretched-link text-decoration-none"
.event__name
#{post.user.name} さん
.text-right
= l post.created_at, format: :long
= render partial: '/posts/posts', collection: @posts, as: :post
each文の中に、renderとオプションでcollectionを使っている形になっている。
この書き方だと、先述の通り、一つのpostにイイねボタンがいくつもついてしまう。
原因を調べていると発見した、とてもrenderとオプションについてまとめてあるqiitaの記事があるので共有しておきます。
この記事を読んで、collectionオプションは変数に自動でeachメソッドを使ってくれていることに気付き、renderの記述を修正。
index.html.haml
= render partial: '/posts/posts', locals: {post: post}
/# これにより、元々あったeach文の中の変数postを部分テンプレートに渡せる。
まとめ
イイね機能の実装を通じて、
collection, locals, object, as, などのオプションの理解が深まった。
エラーの数だけ成長がある!!!