2014-12-02 28 views
0

我加載的數據是這樣的:Rails - 如何計數從ActiveRecord加載的數據?

@cars = Car.includes(:car_services, :services).where(...) 

當我需要從那裏得到的只有唯一的數據,我做這種方式:

<% @cars.uniq_by {|x| x["brand"]}.each do |car| %> 
    <%= I'd need to print out here the count of cars for 'car.brand' from '@cars' %> 

我怎麼能這樣做?我在想這樣做這樣的事情:

@cars = Car.includes(:car_services, :services).where(...) 
@cars2 = @cars 

,然後在循環使用car.brand@cars2搜索,但是這不會是可能很有效...什麼是實現這一目標的最佳途徑?

+0

嗨!你能否詳細說明一下:「然後在循環中使用car.brand並在@ cars2中搜索,」 – 2014-12-02 19:19:05

回答

0

如果我正確地得到您的問題,這應該工作:

<% @cars.pluck(:brand).uniq.each do |brand|%> 
     <%= @cars.where(brand: brand).count %> 
    <% end%> 

雖然,我寧願而不是移動在視圖中有它的這個邏輯,汽車模型

2

您可以使用:Hash[@cars.group_by(&:brand).map {|k,v| [k,v.length]}]

它將返回一個hash組成的所有品牌與其各自的數量

然後,你可以做一些像這則:

<% arr = Hash[@cars.group_by(&:brand).map {|k,v| [k,v.length]}] %> 
<% @cars.uniq_by {|x| x["brand"]}.each do |car| %> 
    <%= arr["#{car.brand}"] %> 
<% end %> 
+0

謝謝你的回答,它正在工作。我還需要同樣保存這些記錄的ID(汽車ID),所以字符串看起來像這樣:'1,2,5,10'。這個怎麼做?非常感謝你。 – user984621 2014-12-02 22:50:07

0

不知道如果我理解你的權利,但是這應該做的伎倆:

@cars.group(:brand).count 

通過SQL做的一切,並返回一個哈希以品牌爲重點,並算作值:

# => { 'Audi' => 123, 'BMW' => 321, ... } 
相關問題