has_manyとhas_many throughでの取得できるデータの違い
class User < ApplicationRecord has_many :posts end
@user.posts
=> @userのidとpostテーブルのuser_idに一致するpostsを取得。
つまり、@userが作成したpost全てを取得
class User < ApplicationRecord has_many :posts, through: :likes end
@user.posts
=> @userのidとlikeテーブルのuser_idに一致するlikesを取得し、そのuser_idに紐付くpost_idからpostをlike経由で取得。
つまり、@userがlikeしたpost全てを取得。
このふたつを併記はできない。(呼び出し方が@user.postsで同じになるため。)
この為呼び出し方を変えての定義が必要。
以下はhas_many :posts, through: :likesを書き換えた場合
class User < ApplicationRecord has_many :posts has_many :like_posts, through: :likes, source: :post # has_many :posts, through: :likes の書き換え # @user.like_postsで呼び出し。 end