我有以下关联:
预订 - has_many reservation_occupations ReservationOccupations - has_many reservation_occupants ReservationOccupants
我想进行以下查询:
1 - 获取一次预订的占用人数 2 - 获取一组预订的占用者数量(例如,Reservations.all)
提前致谢!
答案 0 :(得分:1)
1 - 获取一次预订的占用人数
首先,从Reservation到ReservationOccupant添加has_many :through
关联:
class Reservation < ActiveRecord::Base
has_many :reservation_occupations
has_many :reservation_occupants, through: :reservation_occupations
end
现在你可以简单地做
reservation = Reservation.first
reservation.reservation_occupants.count
2 - 获取一组预订的占用人数
首先,添加更多关联:
class ReservationOccupant < ActiveRecord::Base
belongs_to :reservation_occupation
has_one :reservation, through: :reservation_occupation
end
和
class ReservationOccupation < ActiveRecord::Base
belongs_to :reservation
# ...
end
然后,要计算一组预订的占用者数量,您可以在Reservation
课程中添加以下方法:
class Reservation < ActiveRecord::Base
# ...
def self.num_occupants(reservations)
ReservationOccupant
.joins(:reservation_occupation)
.joins(:reservation)
.where("reservations.id": reservations)
.count
end
end
值得注意的是,无论num_occupants
是预订集合还是单个预订,此reservations
方法都有效。换句话说,这个方法可以用于你的两个问题,#1和#2。但是,第一种方法可以生成更高效的SQL查询,并且可以说更清晰一点,所以在查找单个预留的占用者数量时,我个人会使用它。