In the application I'm building, I want to have Events. People can then register for the event by creating a team, by directly registering for an event (no team), or by joining an existing team. I originally set it up as Event has_many teams, Team has_many users, user belongs_to Team and Event. However, I foresee problems if a registered user wants to join another event (or team for another event), and also when trying to list things like @user.events or @user.teams in the control panel. Someone suggested using a join table and creating a Registration model/migration to join these. Can I have a join model that belongs to Event, Team, and User? Am I approaching this all wrong?
+2
A:
You can create a the join model Registration, and make the belongs_to polymorphic so that it can refer to any type of object. Here's an example:
models/team.rb:
class Team < ActiveRecord::Base
has_many :registrations, :as => :owner
end
models/user.rb
class User < ActiveRecord::Base
has_many :registrations, :as => :owner
end
models/registration.rb
class Registration < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
end
models/event.rb
class Event < ActiveRecord::Base
has_many :registrations
end
db/migrations/1234_add_registrations.rb
...
t.belongs_to :owner, :polymorphic => true
t.belongs_to :event
...
Now you can look at look into registrations to see who has signed up for your event. You can use has_many :events, :through => :registrations, :source => :owner to get back to users, but note that there are some limitations, like has_many :owners, :through => :registrations, that are addressed in plugins like has_many_polymorphs.
Sam C
2010-07-28 03:41:10