1
votes

I would like to have one model (event) that has multiple polymorphic HABTM associations to the same user model.

It should work something like this:

Event < ActiveRecord::Base
  has_many :admin_users, :through => :event_users, :source => :userable, :source_type => 'User'
  has_many :participating_users, :through => :event_users, :source => :userable, :source_type => 'User'
  has_many :paid_users, :through => :event_users, :source => :userable, :source_type => 'User'
  has_many :done_users, :through => :event_users, :source => :userable, :source_type => 'User'
end

class EventUser < ActiveRecord::Base
  belongs_to :userable, :polymorphic => true
  belongs_to :event
end

User < ActiveRecord::Bas
  has_many :event_users, :as => :userable
  has_many :events, :through => :event_users
end

This almost works!! The problem is though that userable_type gets the type "User" for all diffrent associations. Is it possible to solve this?

1

1 Answers

0
votes

I'm afraid your associations look totally wrong. First of all, if you have a 'has_many' on one side of a association, you have to have a 'belongs_to' on the other side. Secondly, I'm guessing done_user, admin_user etc inherit from User. Am i correct ?

And how different are participating_user, admin_user etc different from each other? Do you really need classes for each of these, can you make do with named scopes? I would suggest you simplify your data model. Right now your modeling looks fuzzy. Please do elaborate.

EDIT

Honestly, I think your modeling is over complicated. If I were you, given your descriptions of *_users, I would just have named scopes to retrieve that type of an user. So in effect

class Event < ActiveRecord::Base
  has_many :event_users
  has_many :users, :through => :event_users
end

class User < ActiveRecord::Base
  has_many :event_users
  has_many :events, :through => :event_users
end

So now, write named scopes in your User model to retrieve *_user. Here's an excellent screencast on named_scopes.