Ryan
Ryan

Reputation: 11706

Rails 3 Sum Product of two fields

I need to calculate the sum of the product of two fields in my Rails 3 app (i.e. the equivalent to Excel's sumproduct function). Is there a method in Rails that will help with this and if not, then what would be the rails code using custom sql?

For example, a Hotel has many Rooms. A Room has attributes of sqft (square feet), quantity (of that size) and hotel_id. I would like to calculate the total sqft of all the Rooms in a given Hotel. In SQL, for a Hotel.id = 8, I believe the following statement will work:

select sum(rooms.sqft * rooms.quantity) as SumSqft from rooms inner join hotels on rooms.hotel_id = hotels.id where hotels.id = 8;

Upvotes: 6

Views: 1944

Answers (2)

Joe Half Face
Joe Half Face

Reputation: 2333

def calculate
  @hotel=Hotel.find(params[:id]
  @rooms=Room.all.where(:hotel_id=>@hotel.id)
  sum=0
  @rooms.each do |room|
    sum=sum+room.sqft*room.quantity
  end
  return sum
end

Upvotes: 0

Anthony Alberto
Anthony Alberto

Reputation: 10395

Yep :

Room.where(hotel_id: 8).sum("sqft * quantity")

Upvotes: 18

Related Questions