简体   繁体   English

Ruby on Rails has_many:通过多态关联

[英]Ruby on Rails has_many :through in a polymorphic association

I have searched and searched and found only partial solutions to my current question. 我进行了搜索,发现了当前问题的部分解决方案。

The thing is, I'd like to know if it is possible to use has_many :through along with a polymorphic association in Ruby on Rails. 问题是,我想知道是否可以使用has_many:through以及Ruby on Rails中的多态关联。

I have a system where students can create travel plans (that can belong to many students ) and refund claims (that can belong to only one student ) for their projects. 我有一个系统, students可以为他们的项目创建travel plans (可以属于许多students )并refund claims (只能属于一名student )。 In this system, both admin users and students are able to comment on the plans and claims. 在此系统中, admin usersstudents都可以对计划和声明进行评论。

My associations are: 我的关联是:

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

My questions are: 我的问题是:

Is it correct to associate comments twice in the Student model? Student模型中两次关联comments是否正确?

I don't want the AdminUsers to have travel plans and refund claims , how can I identify their comments as being made on a travel plan or on a refund claim ? 我不想AdminUserstravel plansrefund claims ,我怎么能确定他们的comments作为对正在进行travel plan或在refund claim

Would there be a better approach? 会有更好的方法吗?

Thanks a lot in advance for everyone! 在此先感谢大家!

Cheers, 干杯,

Is it correct to associate comments twice in the Student model? 在学生模型中两次关联评论是否正确?

No, not really. 不,不是。 If you have duplicate association name, you can only use one of them. 如果您有重复的关联名称,则只能使用其中之一。 If you want to use both, you have to name them differently. 如果要同时使用两者,则必须使用不同的名称。

You probably want to add an polymorphic author attribute to the Comment model. 您可能要向Comment模型添加多态author属性。 Than you just need has_many :comments, as: :author to the Student and AdminUser model. 比您只需要has_many :comments, as: :authorStudentAdminUser模型。

If this is a new application and you are starting on the green field you might want to rethink your models a bit and add a Role and a User model. 如果这是一个新应用程序,并且您是从绿色领域开始,则可能需要重新考虑模型并添加一个RoleUser模型。 Student would than be a role of user as would AdminUser be. AdminUser一样, Student将是userrole

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM