user984621
user984621

Reputation: 48483

Rails - how to count data loaded from ActiveRecord?

I am loading data like this:

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

And when I need to get only unique data from there, I do it this way:

<% @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' %>

How can I do that? I was thinking about doing something like this:

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

and then in the cycle to use car.brand and search in @cars2, but that wouldn't be probably very effective... What would be the best way to achieve this?

Upvotes: 0

Views: 96

Answers (3)

Milan K&#246;pke
Milan K&#246;pke

Reputation: 1133

Not sure if I understood you right, but this should do the trick:

@cars.group(:brand).count

Does everything via SQL and returns a hash with the brand as key and count as value:

# => { 'Audi' => 123, 'BMW' => 321, ... }

Upvotes: 0

Aaditi Jain
Aaditi Jain

Reputation: 7027

If I am getting your question correctly this should work:

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

Though, I would prefer moving this logic to Car model instead of having it in views

Upvotes: 0

Waleed
Waleed

Reputation: 776

You can use: Hash[@cars.group_by(&:brand).map {|k,v| [k,v.length]}]

It will return a hash consisting of all the brands with their respective count

You can then do something like this then:

<% 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 %>

Upvotes: 2

Related Questions