如何使用 Rails 3 / MetaSearch 在查询中选择 SUM?
我有一个 Rails 3 应用程序,其中我的模型包括所有者和属性,每个所有者代表拥有一个或多个属性的个人或机构。
我希望能够搜索我的数据库(SQLite3)并返回按所有者分组的结果。对于每个组,我想显示:
- 所有者的姓名(我可以轻松做到这一点) -属于该所有者的符合搜索条件的房产总数(即计数)。 - 上一列中计数的所有属性的总值(即总和)。
所有者拥有许多属性,并且属性属于所有者。另外,“值”是属性的属性。
我正在使用 MetaSearch gem,我可以让它正确返回属性集合。我还可以让它按所有者对结果进行分组,但我不知道如何显示属性的数量及其总价值。
下面是返回属性列表的代码:
@search = Property.group("owner_id").search(params[:search])
我尝试将 .select 添加到链中,如下所示:
@search = Property.select("SUM(value) as mysum").group("owner_id").search(params[:search])
但当我尝试时,我无法访问此总和。有谁知道处理这种情况的有效方法?
I have a Rails 3 application where my model includes Owners and Properties, each Owner representing a person or institution that owns one or more properties.
I would like to be able to search my database (SQLite3) and return the results grouped by owner. For each group, I would like to display:
-The owner's name (I can do this easily)
-The total number of properties belonging to this owner that meet the search conditions (i.e., a count).
-The total value of all the properties counted in the previous column (i.e., a sum).
Owner has_many Properties, and Property belongs_to Owner. Also, "value" is an attribute for Property.
I am using the MetaSearch gem, and I can get it to return a collection of properties correctly. I can also get it to group the results by owner, but I can't figure out how to display the number of properties and their summed value.
Here is the code to return the list of properties:
@search = Property.group("owner_id").search(params[:search])
I have tried adding a .select to the chain like this:
@search = Property.select("SUM(value) as mysum").group("owner_id").search(params[:search])
But I can't access this sum when I try. Does anyone know of an efficient way of handling this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我意识到这已经很旧了,但它在谷歌搜索结果中的排名很高。
您可以简单地调用 sum 。查看您的示例,以下内容大约是您要查找的内容:
http://guides。 rubyonrails.org/active_record_querying.html#sum
I realize this is old, but it's high in google search results.
You can simply call sum. Looking at your example, the following is approx what you're looking for:
http://guides.rubyonrails.org/active_record_querying.html#sum