Ruby on Rails has_many :通过多态关联

Ruby on Rails has_many :through in a polymorphic association

我搜索了又搜索,只找到了我当前问题的部分解决方案。

问题是,我想知道是否可以使用 has_many :through 以及 Rails 上的 Ruby 中的多态关联。

我有一个系统,其中 students 可以创建 travel plans(可以属于多个 students)和 refund claims(可以只属于一个 student) 用于他们的项目。在这个系统中,admin usersstudents 都可以对计划和索赔发表评论。

我的联想是:

class Student < ActiveRecord::Base
   has_and_belongs_to_many :travel_plans
   has_many :refund_claims
   has_many :comments, through: :travel_plans
   has_many :comments, through: :refund_claims
end

class AdminUser < ActiveRecord::Base
   has_many :comments
end

class TravelPlan < ActiveRecord::Base
   has_and_belongs_to_many :students
   has_many :comments, as: :commentable
end

class RefundClaim < ActiveRecord::Base
   belongs_to :student
   has_many :comments, as: :commentable
end

class Comment < ActiveRecord::Base
   belongs_to :commentable, polymorphic: true
end

我的问题是:

Student模型中关联两次comments是否正确?

我不希望 AdminUserstravel plansrefund claims,我怎样才能确定他们的 comments 是在 travel plan 上制作的或 refund claim?

会有更好的方法吗?

先谢谢大家了!

干杯,

Is it correct to associate comments twice in the Student model?

不,不是真的。如果您有重复的关联名称,则只能使用其中一个。如果你想同时使用两者,你​​必须以不同的方式命名它们。

您可能想要向 Comment 模型添加多态 author 属性。比你只需要 has_many :comments, as: :authorStudentAdminUser 模型。

如果这是一个新的应用程序,并且您是从绿色领域开始的,您可能需要稍微重新考虑您的模型并添加一个 Role 和一个 User 模型。 Student 会是 userrole,就像 AdminUser 一样。