Rails模型关系:通过和:has_many

时间:2012-12-27 20:47:55

标签: ruby-on-rails ruby-on-rails-3 model

我有以下模型(仅包含主要详细信息),其中有Courts,其时间被分为CourtTimeSlotsreserved可能Users - 更多或更少描述如下 我该如何建立这种关系? User应该有多少CourtTimeSlots:通过Reservation

目的是能够获取所有预订,并从那里显示UserCourt信息。

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

1 个答案:

答案 0 :(得分:2)

我明白了。在这种情况下,以下内容可以实现您的目标,演示如何通过预订访问您要查找的数据。

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