Help us understand the problem. What is going on with this article?

Rails ArticleModelにlike_numberとstock_numberをインスタンス変数として格納する

コード

# frozen_string_literal: true

class Article < ApplicationRecord
  # attr_accessor :like_number, :stock_number 下で定義する場合、要らない

  def like_number
    @like_number = ArticleLike.where(article_id: id).count
  end

  def stock_number
    @stock_number = ArticleStock.where(article_id: id).count
  end

  def comment_number
    @comment_number = Comment.where(article_id: id).count
  end
end

本当にこれでいい??

確認

[3] pry(main)> article = Article.find(1)
[4] pry(main)> article.like_number
   (0.4ms)  SELECT COUNT(*) FROM `article_likes` WHERE `article_likes`.`user_id` = 1
=> 10

参考

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away