Search code examples
ruby-on-railsruby-on-rails-4activerecordmodel-associations

Explanation on Rails Associations - Rails 4


i'm new to rails and your help and advise would be much appreciated as i am finding this challenging

Aim: i want the creator of the event to be able to select more than one user as hosts for a created event (just like how facebook allows the creator of a page to be be able to select users as admins of a created page). Is the below how my model and schema should be displayed?

i was aiming to build something like this image. Event1 i can select Ian & Jesse as hosts, Event2 i can also select Ian again as a host and select Emma

enter image description here

This is how i imagine it so far to be built (your guidance would be much appreciated):

models
user.rb
has_many events

event.rb
belongs_to user

host.rb
belongs_to user
has_many events

schema

users
name
email

events
title
address
user_id

hosts
user_id
event_id

Solution

  • Started writing this as a comment but realised it was getting too wordy.

    your model is broken ... an event has many users .. it doesn't belong_to a single user.

    What you have is a many to many relationship between users and events which needs resolving through a join table (aka associative/junction table). You have gone some way to resolving this with the hosts table though this goes against the rails convention.

    What you want is something like:

    models

    user.rb

    has_and_belongs_to_many :events
    

    event.rb

    has_and_belongs_to_many :users
    

    and create a join table that references the two models

    users table
      name
      email
    
    events table
      title
      address
    
    events_hosts table
      user_id
      event_id
    

    The rails convention is for the join table to be named by joining the two names of the tables it is joining lexically ordered - i.e. events before hosts, concatenated together to give events_hosts.

    Alternatively, you can also create a join model if you prefer:

    EventHost
    
    belongs_to :user
    belongs_to :event
    

    and modify the has_and_belongs_to_many to has_many :event_hosts in the other two models - the database schema will remain the same.