ESoft
ESoft

Reputation: 862

Rails model relationship :through and :has_many

I have the following model (only included major details) where there are Courts and their time are split into CourtTimeSlots which may be reserved by any Users - more or less described below.
How do I set up such a relationship? Should User have many CourtTimeSlots :through Reservation?

The aim is to be able to get all reservations and from there display the User and Court information.

class User < ActiveRecord::Base
end

class Reservation < ActiveRecord::Base
    ???
end

class Court < ActiveRecord::Base
    attr_accessible :court_number
    has_many :court_sessions
end

class CourtTimeSlot < ActiveRecord::Base
    attr_accessible :start_time, :end_time, :status
end

Upvotes: 1

Views: 91

Answers (1)

kries
kries

Reputation: 199

I see. In that case, the following may achieve your goal, demonstrating how to access the data you are looking for through the reservation.

class Reservation < ActiveRecord::Base
  belongs_to :time_slot
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :reservations
end

class CourtTimeSlot < ActiveRecord::Base
  has_one :reservation
  belongs_to :court
end

class Court < ActiveRecord::Base
  has_many :court_time_slots
end

Reservations.all.each do |r|
  r.user
  r.time_slot.court.court_name
end

Upvotes: 2

Related Questions