mosquito242
mosquito242

Reputation: 353

group and count by nested association in rails

So I have the following associations (An Order comes from a Catch that is of a fish).

I want to, group a set of orders by the fish they are of, and then sum the quantity ordered attribute within order for each group.

I can do it for each catch with

Order.all.group(:catch_id).sum(:qty_ordered)

but not for the fish.

class Order < ActiveRecord::Base
    belongs_to :user
    belongs_to :catch
end

class Catch < ActiveRecord::Base
    has_many :orders
    belongs_to :fish
end

class Fish < ActiveRecord::Base
    has_many :catches
end

Any tips?

Upvotes: 2

Views: 3468

Answers (1)

Beartech
Beartech

Reputation: 6411

You are doing this: Order.all.group(:catch_id).sum(:qty_ordered)

and it works because Order has a field called catch_id, so you can group by that field.

If you want to group by fish_id you would have to have a column fish_id in Orders and Orders would have a belongs_to :fish association.

To group_by another related column it would be something like this:

Order.all.group_by {|order| order.catch.fish}

This is not the same group function, this is the Enumerable function group_by. Since your query returns an enumerable, it can be used. It will return a hash with each key being a Fish object, and the value being an array of Order objects that have that fish in them. This may not be the dataset you are looking for. Also you will not be able to just chain a .sum onto it.

You need to look at your model relations and either use a relation that exists to get the data you want, or create more associations to be able to pull the data you want. An example of the exact data set you want would help determine your needs.

An aside, using Order as a model may not be the best form. Rails has a method .order and you might find a conflict somewhere along the way.

Upvotes: 1

Related Questions