Fabiano Paiva
Fabiano Paiva

Reputation: 3

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.

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,

Upvotes: 0

Views: 337

Answers (2)

wintermeyer
wintermeyer

Reputation: 8318

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.

Upvotes: 1

Marek Lipka
Marek Lipka

Reputation: 51151

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.

Upvotes: 0

Related Questions