How to select SUM in a query using Rails 3 / MetaSearch?

I have a Rails 3 application in which my model includes Owners and Properties, each representing a person or institution with one or more properties.

I would like to be able to search in my database (SQLite3) and return the results grouped by the owner. For each group, I would like to display:

- Name of the owner (I can do this easily) - The total number of properties belonging to this owner that match the search conditions (i.e. Account). is the total value of all the properties considered in the previous column (i.e., Amount).

The owner is has_many Properties, and the property is owned by _ owner. In addition, “value” is an attribute for a property.

I use the MetaSearch stone, and I can get it to return the property set correctly. I can also get it to group the results from the owner, but I cannot figure out how to display the number of properties and their total value.

Here is the code to return the property list:

@search = Property.group("owner_id").search(params[:search])

I tried adding .select to the chain as follows:

@search = Property.select("SUM(value) as mysum").group("owner_id").search(params[:search])

But I can’t access this amount when I try. Does anyone know of an effective way to solve this situation?

+5
source share
1 answer

I understand that this is old, but it is high in Google search results.

You can just name the amount. If you look at your example, then something like this:

Property.where(SEARCH_VALUES).sum(:value).group(:owner_id)

http://guides.rubyonrails.org/active_record_querying.html#sum

+11

All Articles