I'm trying to write an app that allows users to sign up for events. Every event has its owner and users that are planning to attend the event. I'm having trouble choosing the right association for the latter. I've tried has_and_belongs_to_many, but read somewhere that it's not recommended to use it, so I tried with has_many :through and it doesn't seem to work. This is what I came up with for now:
class User < ApplicationRecord
has_secure_password
has_many :events, :foreign_key => :owner_id
has_many :event_users
has_many :events, :through => :event_users
end
class Event < ApplicationRecord
belongs_to :user, :foreign_key => :owner_id
has_many :event_users
has_many :users, :through => :event_users
end
class EventUser < ApplicationRecord
has_many :users
has_many :events
end
And the signup code looks like this:
def sign_up
user = User.find(session[:user_id])
@event.users << user
end
This code returns an error:
Cannot modify association 'Event#users' because the source reflection class 'User' is associated to 'EventUser' via :has_many.
Can you guys tell me what I'm doing wrong and how to do it right? It's my first serious Rails app and I really want to write it the right way. Thanks in advance.
You probably want to distinguish the owner from the guests. I'd do this:
#models/event.rb
belongs_to :owner, class_name: "User"
has_many :guests, class_name: "User", through: :event_users
has_many :event_users
#models/eventuser.rb
belongs_to :users
belongs_to :events
#models/user.rb
has_many :event_users
has_many :events, through: :event_users
has_many :event_ownerships, class_name: "Event"
Super important point here is EventUser(s) are belongs_to to have the many to many relationship you indicated.
Also, You can't redefine the user.events association, you need to rename it.