Many to many and one to many association between same models

41 views Asked by At

I am creating a simple Sinatra app, using Sequel for my ORM. Most of the data revolves around users and events where:

  • An event can have many users, one of which is the "owner".
  • Users can have many events, one or many of which they "own".

Here is a simplified version of my schema/model definitions:

class User < Sequel::Model(:users)
  many_to_many :events
  one_to_one :event
end

class Event < Sequel::Model(:events)
  many_to_many :users
  many_to_one :user
end

# provides a link between users and events
# e.g. event.users or user.events
# I am unsure how necessary this is :)
db.create_table :events_users do
  primay_key :id
  foreign_key :event_id, :events
  foreign_key :user_id, :users
end

This allows me to get the users attached to an event, or the events that a user is attached to, but I am struggling to express the "ownership" of an event. It seems like the following pseudocode would work:

my_user = User.all.first
owned_events = Event.where(user_id = my_user.user_id)

That leads to two questions:

  1. Does the current way i'm using assocations make sense?
  2. How do I express ownership of an event in terms of Sequel's association model?
1

There are 1 answers

3
mie On BEST ANSWER

Maybe something like this:

class Event
  many_to_one :owner, :class=>:User
  many_to_many :users
end

class User
  one_to_many :owned_events, :class=>:Event, :key=>:owner_id
  many_to_many :events
end

You'll need to add owned_id field in events table.

Usage:

user = User.all.first
event = Event.new(:title => 'New Event')
events.add_owner(user)
event.save
another_user = User.create(:name => 'Jack')
event.add_user(another_user)