invaino
invaino

Reputation: 267

Rails 3 - belongs_to user AND has_many users

I am trying to figure out how to do the following :

a Concert belongs_to a user (the creator), has_many guests and has_many organisers.

Is the following approach is good ?

Concert:

 class Concert < ActiveRecord::Base
  belongs_to :user
  has_many :guests, :class_name => 'User'
  has_many :organisers, :class_name => 'User'
 end

User:

 class User < ActiveRecord::Base
  has_many :concerts
 end

Thanks in advance,

Upvotes: 1

Views: 1458

Answers (1)

Harish Shetty
Harish Shetty

Reputation: 64373

Ad two new models to hold the has_many relationships:

 class Concert < ActiveRecord::Base
  belongs_to :user
  has_many   :concert_guests
  has_many   :concert_organizers

  has_many   :guests, :through => :concert_guests, :source => :user
  has_many   :organizers, :through => :concert_organizers, :source => :user
 end

 class User < ActiveRecord::Base
  has_many :concerts
 end

 # table with user_id and concert_id columns   
 class ConcertGuest
   belongs_to :user
   belongs_to :concert
 end

 # table with user_id and concert_id columns   
 class ConcertOrganizer
   belongs_to :user
   belongs_to :concert
 end

Upvotes: 2

Related Questions