0

I'm working on a Rails 5.2 project that stores and manages guest lists. I have Event and Guest models, and they are associated with a HABTM relationship. This works well, but there is a requirement to be able to optionally store a grouping of two guests (i.e: couples) and when adding guests to the guest list, the couple can be selected and added together, without the user having to remember which of the individual guests should be added to the guest list together, for example, when selecting guests to be added to a guest list, a user should be able to select "Sam", "Andrew", "Mary & Joseph".

What would be the best way of achieving this in ActiveRecord?

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

Any help would be much appreciated!

Thanks

simonlehmann
  • 852
  • 1
  • 10
  • 27
  • 2
    Maybe a `has_many - through` relation will be a nice solution. In the through table there will be 3 columns. **event_id**, **guest_id**, **couple_id** (which will be a guest_id) – Emu Jul 24 '18 at 05:01
  • @Emu's suggestion should solve your purpose if you have a model `Couple` in your application. Guide: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association – Jagdeep Singh Jul 24 '18 at 06:06
  • I think it would be even better to use a Polymorphic association on the EventGuest model, in which you can either assign a Couple or a Guest. https://guides.rubyonrails.org/association_basics.html#polymorphic-associations – bo-oz Jul 24 '18 at 06:28

1 Answers1

0

You need the following models, untested but you'll get the idea.

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
bo-oz
  • 2,842
  • 2
  • 24
  • 44