Zephyr4434
Zephyr4434

Reputation: 796

Rails - How to calculate average in view with conditions

I have a @shirts variable set in my controller that is an array of all products of a particular Category (so it is @shirts = @category.shirts) in my controller.

Then in my view, I want to be able to calculate the average price of a particular shirt from @shirts based on certain conditions.

So for example, calculate the average price of all shirts where the color is red and the size is small.

I am new to rails so I am not sure if I am taking the right approach. Right now I have in my view:

<%= @shirts.average_price("Red","Small") %>

In my model:

def average_price(color, size)
    self.class.average(:price).where(color: color, size: size)
end

Right now I am getting:

undefined method `average_price'

This aside, is this the best approach to take? There are obviously a number of combinations of sizes and colors and I want to show them all in a table, calculating the average price for each combination. What would be a more DRY way of doing this?

Right now I am manually defining table rows and trying to pass in the conditions for size & color for each row, but the HTMl gets repetitive. Thanks for your help!

Upvotes: 0

Views: 726

Answers (1)

sites
sites

Reputation: 21775

Try this:

def self.average_for(size, color)
  where(color: color, size: size).average(:price)
end

You will use it like this:

@shirts.average_for('small','red')

Your @shirts should not be an array, instead a relation:

class Category...
  has_many :products # or shirts in your case

Upvotes: 1

Related Questions