![](/img/trans.png)
[英]Rails 4: combining has_many :through association with polymorphic association
[英]Ruby on Rails has_many :through in a polymorphic association
我進行了搜索,發現了當前問題的部分解決方案。
問題是,我想知道是否可以使用has_many:through以及Ruby on Rails中的多態關聯。
我有一個系統, students
可以為他們的項目創建travel plans
(可以屬於許多students
)並refund claims
(只能屬於一名student
)。 在此系統中, admin users
和students
都可以對計划和聲明進行評論。
我的關聯是:
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
是否正確?
我不想AdminUsers
有travel plans
和refund claims
,我怎么能確定他們的comments
作為對正在進行travel plan
或在refund claim
?
會有更好的方法嗎?
在此先感謝大家!
干杯,
在學生模型中兩次關聯評論是否正確?
不,不是。 如果您有重復的關聯名稱,則只能使用其中之一。 如果要同時使用兩者,則必須使用不同的名稱。
您可能要向Comment
模型添加多態author
屬性。 比您只需要has_many :comments, as: :author
和Student
和AdminUser
模型。
如果這是一個新應用程序,並且您是從綠色領域開始,則可能需要重新考慮模型並添加一個Role
和User
模型。 與AdminUser
一樣, Student
將是user
的role
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.