Polymorphic Through Relationships

I’m building a site for a school which has a number of activities and groups. Each activity can have a multiple leaders and multiple participants. The groups and activities vary widely - some are events, some are classrooms, some are study groups and some are short-term projects.

Instead of having multiple habtm tables, I thought it would be cleaner to have a single table called ‘participations’ that would look like:

  • participateable_id
  • participateable_type
  • person_id
  • role_id The model structure might look like this -
  • class Person;
  • class Event; has_many :instructors; has_many :students;
  • class StudyGroup; has_one :instructor; has_many :students; I’d love to be able to say @event.students << Person.find(params[:id]) and have a new row created in participations with the correct person and a role id of 2 (let’s say). Then when I write @event.instructors << Person.find(params[:id]) it would create a new row with the person id and a role id of 1. Is this possible using standard rails relationships?

To sum it up, I’m looking for a has_many :through relationship where the “through” is a rails-polymorphic table with one field defined by the relationship (role_id - always the same).

I know how to accomplish this by writing my own methods (which is how I have it now), but I’d like to know if there is a slick way to do this via built-in relationships.

Thanks in advance -

Hi!

I think you will find the answer at Josh Susser's great blog about it http://blog.hasmanythrough.com/articles/2006/08/19/magic-join-model-creation

To sum it up, I'm looking for a has_many :through relationship where the "through" is a rails-polymorphic table with one field defined by the relationship (role_id - always the same).

Priit

That looks promising - and only a few days old. Not bad.