问题描述
我对 rails 还很陌生,正在开发一个应用程序,该应用程序基本上允许用户报告对其他用户的不满(只是一个我想与朋友一起使用的有趣应用程序)。基本上只有两个模型,用户和报告。一个用户有很多报告并且报告属于一个用户(即一个用户与提交的关于他们的报告相关联)
基本模型结构:
class User<ApplicationRecord
has_many :reports
end
class Report<ApplicationRecord
belongs_to :user
end
现在,用户可以提交新报告并从下拉列表中选择要关联的用户,但我还想在报告和提交报告的用户之间添加关联,以便我可以浏览报告用户创建并找到他们报告最多的用户。 (即。我希望用户有很多关于他们的报告,也有很多他们写的关于其他人的报告)
我不知道如何实现这一点,因为我需要将这个 has_many/belongs 与我上面的关系区分开来。有什么想法吗?
解决方法
我认为您想要像 reporter association
这样的东西,这可以通过从 report
表到 user
表的可选引用来实现:
因此在您的 report model
上添加以下行:
belongs_to :reporter,class_name: :User,foreign_key: 'reported_by_id',optional: true
然后生成一个 migration
并添加以下代码:
add_reference :reports,:reported_by,index: true
然后您可以执行以下操作:
report.reporter = user1
report.save
or
user2 = report.reporter
然后获取特定 reports
生成的 user
:
Report.where(reported_by_id: user.id)
This may help with the migration,您可以简单地运行 rails g migration <name_of_your_migration>
,这将生成一个具有该名称的文件,并将上面的代码添加到 change function
中。
上面的例子是在 rails 5.2
上,你所说的修复上面的内容正是:除了关系之外,我作为 report
与表 users
之间,我还有一个与特定用户的特殊关系(如果您的数据库中已有数据,您可以将该关系设为可选或不设为可选,我认为您应该这样做 optional
)。我希望这有帮助! ?