LoginSignup
0
0

More than 5 years have passed since last update.

ファボ数のカウント実装

Posted at

1時間ほど苦しんでしまったので残しておく。

index.html.erb
<% @favorite_posts.each do |post| %>
--- 省略
  <%= post.favorites.count %>
---  省略
<% end %>

postはfavoriteを複数持ち(has_many)、favoriteは一つのpostに属している(belongs_to)

post.rb
has_many :favorites
favorite.rb
belongs_to :post

html内でcountを使用すれば上記の書き方でファボ数を数えてくれた。
最初はコントローラーにpostのidを渡してSQLで同idのファボをCountしてそれを表示・・・とかやろうとしていた。かなり簡単に実装できて驚き。

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