-1
我有以下模型。如何获取关联组中的最新记录
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 %>
所以,我怎么能获得最新的价格为每个供应商(按供应商分组),以一种我可以加载的方式,否则性能会太慢。
组将无法工作,因为它需要的ID。所以我尝试的是select('DISTINCT ON(supplier_id)*')。order('supplier_id,created_at DESC')。但是,您如何在提到的视图中访问它?你如何急于加载? – dc10