对两个记录进行分组并通过ActiveRecord中的HABTM将该组关联滑轨

时间:2018-07-24 04:53:46

标签: ruby-on-rails activerecord rails-activerecord has-and-belongs-to-many

我正在研究存储和管理来宾列表的Rails 5.2项目。我有EventGuest模型,它们与HABTM关系相关联。这很好用,但是需要能够选择性地存储两个来宾(即夫妇)的分组,并且在将来宾添加到来宾列表时,可以选择并添加一对,而用户不必记住哪个应将单个访客的一起添加到访客列表,例如,当选择要添加到访客列表的访客时,用户应能够选择“ Sam”,“ Andrew”,“ Mary&Joseph”。

在ActiveRecord中实现此目标的最佳方法是什么?

class Event < ApplicationRecord
  has_and_belongs_to_many :guests
end
class Guest < ApplicationRecord
  has_and_belongs_to_many :events
end

任何帮助将不胜感激!

谢谢

1 个答案:

答案 0 :(得分:0)

您需要以下未经测试的模型,但是您会明白的。

class Event < ApplicationRecord
  has_many :event_guests
end

class Guest < ApplicationRecord
  has_many :event_guests, :as => :assignable
  has_many :guest_couples
end

class Couple < ApplicationRecord
  has_many :event_guests, :as => :assignable
  has_many :guest_couples
end

# table to relate events to either a Guest or a Couple (polymorhpic)
class EventGuest < ApplicationRecord
  belongs_to :event
  belongs_to :assignable, polymorphic: true
end

# Model to create couples (one-to-many)
class GuestCouple < ApplicationRecord
  belongs_to :guest
  belongs_to :couple
end