Rails 3 - belongs_to用户AND has_many用户

时间:2011-06-06 23:08:13

标签: ruby-on-rails database ruby-on-rails-3 activerecord

我想弄清楚如何执行以下操作:

音乐会属于用户(创作者),has_many来宾和has_many组织者。

以下方法是否合适?

音乐会:

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

用户:

 class User < ActiveRecord::Base
  has_many :concerts
 end

提前致谢,

1 个答案:

答案 0 :(得分:2)

提供两个新模型来保持has_many关系:

 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