Reputation: 537
In my application a user can create an appointment.
class User
has_many :appointments
end
class Appointment
belongs_to :user
end
However, a user can also join another appointment created by another user.
Could someone recommend a way to set up my models?
I've been reading through http://guides.rubyonrails.org/association_basics.html and cannot find the correct association.
I'm really keen to do this the rails way, rather than hacking my application about.
Would has_and_belongs_to_many be the way to go?
Upvotes: 0
Views: 67
Reputation: 16510
Sounds like you probably want to use has_many
with some kind of model describing the relationship between users and appointments:
# models/user_appointment.rb
class UserAppointment < ActiveRecord::Base
belongs_to :user
belongs_to :appointment
end
# models/appointment.rb
class Appointment < ActiveRecord::Base
has_many :user_appointments
has_many :users, :through => :user_appointments
end
# models/user.rb
class User < ActiveRecord::Base
has_many :user_appointments
has_many :appointments, :through => :user_appointments
end
Of course, you'll probably also want to represent the owner of the appointment. You could expand your Appointment
model to reflect who actually owns it. You could provide a relationship field in UserAppointment
to describe whether a user is an owner or subscriber, but it might be easier to simply add a belongs_to
relationship to the appointment model:
# models/appointment.rb
class Appointment < ActiveRecord::Base
has_many :user_appointments
has_many :users, :through => :user_appointments
belongs_to :owner, :class_name => 'User'
end
Upvotes: 1