Userテーブルのカラムが
name
email
college
Productデーブルのカラムが
user_id
product_name
condition
explanation
category
となっています。
また、user.rbに
has_many :products, dependent: :destroy
product.rbに
belongs_to :user
を書いています。
ここで、ログインユーザーのcollegeと等しいcollegeの値を持つProductのデータを抽出し、インスタンス変数として定義したいのですが、綺麗な方法が思い浮かびません。挙動としては、
@product = Product.joins(:users).where(users: { college: current_user.college })
のようなことをしたいです。(実際にはUser側にhas_many :productsを書いているのでできませんが)
やはりProductデーブルにuser_collegeのようなカラムを追加して、紐づけられたUserのcollegeと同じ値を登録し、
@product = Product.where(user_college: current_user.college)
とするしかないのでしょうか?
詳しい方がいたら教えていただきたいです。
あなたの回答
tips
プレビュー