【问题标题】:ActiveRecord association through multiple tablesActiveRecord 通过多个表关联
【发布时间】:2020-03-18 22:14:00
【问题描述】:

我的 Rails 应用程序具有以下架构:

一个项目有很多评论,每个评论都由唯一的用户填写以计算全局分数。

我们可以说“一个用户组织处理许多实体,这些实体拥有许多由用户审查的项目”。

如您所见,我有一个循环引用,因为我链接了“用户”和“评论”表。

经过多次尝试和多次搜索,我无法将用户与评论相关联...这是我到目前为止所做的:

1.创建关联表“UserReviews”

2。模型用户

class User < ApplicationRecord
  belongs_to :organization

  ####

  has_many :user_reviews
  has_many :reviews, through: :user_reviews
end

3.模型审查

class Review < ApplicationRecord
  belongs_to :project

  ##

  belongs_to :user_reviews
  has_one :user, through: :user_reviews
end

4.模型用户评论

class UserReview < ApplicationRecord
  belongs_to :user
  belongs_to :review
end

我希望能够获取 user.reviews 或 review.user。

基本上...我不得不承认,尽管有文档,我还是迷路了。我从来不用处理这类问题。

非常感谢您的帮助!

【问题讨论】:

标签: ruby-on-rails activerecord ruby-on-rails-5 rails-activerecord


【解决方案1】:

这里为什么需要 UserReview 模型?我想 Review 模型足以满足您的用例。

Review 模型更改为:

class Review < ApplicationRecord
  belongs_to :project
  belongs_to :user
end

【讨论】:

  • 这里不需要连接表吗?我认为在这种情况下必须使用“直通”链接?
  • @Aurel 评论基于user_idproject_id 是唯一的。您应该在user_id, project_id 上添加uniqueness 验证
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
  • 2011-06-03
  • 1970-01-01
相关资源
最近更新 更多