我如何在两个模型之间有多个has_many到has_many的关系?

时间:2015-07-17 20:50:52

标签: ruby-on-rails relationship

我对Rails更新,并且对与另一个模型有多种关系的模型有问题。这是我当前的设置,我可以通过UserEvents模型向用户添加事件。然而,显然我不能将这种关系称为事件两次......这就是我难倒的地方。

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

class UserEvents < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class UserParticipating < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class Events < ActiveRecord::Base
  has_one :user_event
  has_one :user, :through => :user_events
  has_many :user_participating
  has_many :user, :through => :user_participating
end

我肯定很有可能将这一切都搞错了,但是,我已经在这里呆了好几个小时了,而且我似乎无处可去。所以,我想我会问。谢谢!

1 个答案:

答案 0 :(得分:1)

class User < ActiveRecord::Base
  has_many :user_events
  has_many :user_participatings
  has_many :events, through: :user_events
  has_many :participating_events, through: :user_participatings, class_name: 'Event'
end

class UserEvents < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class UserParticipating < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class Events < ActiveRecord::Base
  has_one :user_event
  has_one :user, through: :user_events
  has_many :user_participatings
  has_many :participants, through: :user_participatings, source: :user
end

即使我发现了一个事件has_one用户,我也不明白为什么你需要UserEvent