【问题标题】:Count distinct pairs of attributes in Rails计算 Rails 中不同的属性对
【发布时间】:2018-11-27 13:50:09
【问题描述】:

我有一个班级RestaurantRestaurant(id: integer, name: string, url: string, address: string

我想得到urlname 的所有不同组合并计算它们。我该怎么做?

我试过了

Restaurant.select(:url, :name).distinct.count

但我明白了:

No function matches the given name and argument types. You might need to add explicit type casts.

【问题讨论】:

  • 它适用于我的模型。????只是出于好奇,请尝试Restaurant.all.select(:url, :name).distinct
  • 对不起。我忘了添加导致错误的.count

标签: ruby-on-rails


【解决方案1】:

你试过了吗?

Restaurant.pluck(:url, :name).uniq.count

更多http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck

还要检查这个问题Rails: select unique values from a column

【讨论】:

  • 更多关于计算uniq字段stackoverflow.com/questions/36608/…
  • 错误答案,上面将首先查询所有记录到内存中,然后计算 Ruby 内部的唯一组合,而不是 db。正确的做法是:Restaurant.count("DISTINCT(url, name)")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 2020-02-13
相关资源
最近更新 更多