与 3 个模型的 Rails 关联

胜利者

使用 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_idreviews.profile_id确保唯一性。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章