依靠第三级相关模型

时间:2015-12-26 17:42:12

标签: ruby-on-rails-4 activerecord

我有以下关联:

预订 - has_many reservation_occupations ReservationOccupations - has_many reservation_occupants ReservationOccupants

我想进行以下查询:

1 - 获取一次预订的占用人数 2 - 获取一组预订的占用者数量(例如,Reservations.all)

提前致谢!

1 个答案:

答案 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查询,并且可以说更清晰一点,所以在查找单个预留的占用者数量时,我个人会使用它。