使用 Rails 6。这是我想要实现的目标:
这是我的协会不起作用:
class Shop < ApplicationRecord
has_many :reviews, dependent: :destroy
end
class Profile < ApplicationRecord
belongs_to :user
has_many :reviews
end
class Review < ApplicationRecord
belongs_to :shop, counter_cache: true
belongs_to :profile, counter_cache: true
end
class User < ApplicationRecord
has_one :profile, dependent: :destroy
end
在这里不起作用的是 - 作为current_user
(与profile
,因此current_user.profile
),我如何获得商店对当前用户的评论?从技术上讲,应该返回一篇评论。
class User < ApplicationRecord
has_one :profile, dependent: :destroy
has_many :reviews, through: :profile
end
current_user.reviews.find_by(shop: @shop)
要么
@shop.reviews.find_by(profile: current_user.profile)
这假设您实际上已经添加了复合索引reviews.shop_id
并reviews.profile_id
确保唯一性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句