Reputation: 725
I am having trouble wrapping my mind around this. My goal is to create the simplest following relationships:
So far, my approach has been with 4 models:
class Event < ApplicationRecord
belongs_to :poster, class_name: "User"
has_many :hosts, class_name: "User"
has_many :votes, foreign_key: 'voted_id', dependent: :destroy
has_many :upvoters, through: :votes, source: :voter
class User < ApplicationRecord
has_many :posts, class: "Event"
has_many :votes, foreign_key: 'voter_id', dependent: :destroy
has_many :upvotes, through: :votes, source: :voted
class Vote < ApplicationRecord
belongs_to :voter, class_name: "User"
belongs_to :voted, class_name: "Event"
class Membership < ApplicationRecord
belongs_to :user
belongs_to :event
Is there a way I can utilize the Membership class for each of the following relationships (except voting)?
Upvotes: 0
Views: 80
Reputation: 3005
You can try something like this:
class Membership < ApplicationRecord
belongs_to :user
belongs_to :event
enum type: [ :host, :reservation, :attendance ]
end
class Event < ApplicationRecord
belongs_to :poster, class_name: "User"
has_many :host_memberships, -> { host }, class_name: "Membership"
has_many :reservation_memberships, -> { reservation }, class_name: "Membership"
has_many :attendance_memberships, -> { attendance }, class_name: "Membership"
has_many :hosts, through: :host_memberships, source: "User"
has_many :reservations, through: :reservation_memberships, source: "User"
has_many :attendees, through: :attendance_memberships, source: "User"
end
class User < ApplicationRecord
has_many :posts, class_name: "Event"
has_many :host_memberships, -> { host }, class_name: "Membership"
has_many :reservation_memberships, -> { reservation }, class_name: "Membership"
has_many :attendance_memberships, -> { attendance }, class_name: "Membership"
has_many :hosted, through: :host_memberships, source: "Event"
has_many :reservations, through: :reservation_memberships, source: "Event"
has_many :attended, through: :attendance_memberships, source: "Event"
end
Upvotes: 0