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.
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. In this system, both admin users
and students
are able to comment on the plans and claims.
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?
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
?
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. Than you just need has_many :comments, as: :author
to the Student
and AdminUser
model.
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. Student
would than be a role
of user
as would AdminUser
be.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.