我有以下型号。
class Candidate < ActiveRecord::Base
belongs_to :accommodation
has_many :rates, :foreign_key => :candidate_id
end
class Accommodation < ActiveRecord::Base
has_many :rates, :through => :candidates
end
class Rate < ActiveRecord::Base
belongs_to :candidate
delegate :accommodation, :to => :candidate
end
class City < Location
has_and_belongs_to_many :accommodations, :foreign_key => 'location_id'
end
现在我获得了所有位置,以便迭代它们并获得所有位置及其住宿和费率。问题是我希望只有最近的住宿费率,但是按照名为:supplier_id的列分组 在我看来:
<% acc.rates.each do |rate| %>
<div class="rate">
<div class="">
<h3>
<%= rate.promo %>
<small><%= rate.supplier %></small>
<span class="rate-price text-right"><strong><%= rate.try(:nightly_rate).try(:ceil) %></strong></span>
<small>€</small>
</h3>
</div>
</div>
<% end %>
那么我怎样才能获得每个供应商的最新费率(按供应商分组),以一种我可以加载的方式,否则性能会太慢。
答案 0 :(得分:0)
我认为您需要在2个单独的查询中划分此查询:
locations = Location.includes(:accomodations)
accomodation_ids = locations.map(&:accomodation_ids).flatten
rates = Rate.by_accomodation_and_supplier(accomodation_ids)
class Rate
def self.by_accomodation_and_supplier(accomodation_ids)
joins(candidate: { accomodation: accomodation_ids}).
order(created_at: :desc).group(:supplier_id)
end
end