以下是" Hotel"的方法。用于查找关于事务和用户的top_spender的模型。
def top_spenders
top_spenders = []
self.transactions.group(:user_id).sum(:amount, :order => 'SUM(amount) DESC', :limit => 5).each do |record|
person = User.find(record.first).name
amount = record.second
person_amount = [person, amount]
top_spenders << person_amount
end
top_spenders
end
### hotel.rb
has_many :transactions
### transaction.rb
belongs_to :user
belongs_to :hotel
提供弃用警告的行是:
self.transactions.group(:user_id).sum(:amount, :order => 'SUM(amount) DESC', :limit => 5)
弃用警告如下:
DEPRECATION WARNING: Relation#calculate with finder options is deprecated. Please build a scope and then call calculate on it instead. (called from top_spenders ...
DEPRECATION WARNING: The :distinct option for `Relation#count` is deprecated. Please use `Relation#distinct` instead. (eg. `relation.distinct.count`). (called from top_spenders ...
我确实尝试为分组事务添加范围,然后在其中查询sum,但警告仍然存在。此外,尝试了其他一些方法,但无法满足要求的弃用。
任何帮助都会受到很大的赞赏。
答案 0 :(得分:1)
self.transactions.group("user_id").select("user_id, sum(amount) as total_amount").order("sum(amount) DESC").includes(:user)
这修复了弃用警告并启用了预先加载。感谢Rails 4. :)