Search code examples
ruby-on-railsactiverecordassociationshas-manybelongs-to

Database Association, Can a class has_many and belong_to the same object?


So I'm trying to create a simple events web application where class User can both create class Event and participate in them. In the case class User creates a class Event, I want that event to belong_to the user. But in case that same User signs up to participate in another event, I want the user to belong_to the event, and that event to has_many Users. I don't know how this would actually be written in the models though.

In one case class User is a participant belonging to the event, and in the other they are the host and the event belongs_to them. I wan't to keep this dry and not create separate classes of users(host and participant in this case) if I don't have too. A mere joint table doesn't seem to account for this conditional association. Any advice on the best way to do this?

class User ???

class Event ????

Thanks!


Solution

  • You'll need to make 2 associations - one to link to created Events, and one to link to subscribed Events:

    create_table :event_subscriptions do |t|
      t.references :subscribed_user
      t.references :subscribed_event
    end
    
    create_table :events do |t|
      t.references :user
      # other fields
    end
    
    class User < ActiveRecord::Base
      has_many :events               # created Events
      has_many :event_subscriptions, :foreign_key => :subscribed_user_id
      has_many :subscribed_events, :through => :event_subscriptions  # subscribed Events
    end
    
    class EventSubscription < ActiveRecord::Base
      belongs_to :subscribed_user, :class_name => 'User'
      belongs_to :subscribed_event, :class_name => 'Event'
    end
    
    class Event < ActiveRecord::Base
      belongs_to :user               # the creating User
      has_many :event_subscriptions, :foreign_key => :subscribed_event_id
      has_many :subscribed_users, :through => :event_subscriptions   # subscribed Users
    end