1

以下是“酒店”模型中用于查找与交易和​​用户相关的 top_spenders 的方法。

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 ...

我确实尝试为分组事务添加范围,然后在其中查询总和,但警告仍然存在。此外,尝试了其他一些方法,但无法避免在满足要求的情况下弃用。

任何帮助将不胜感激。

4

1 回答 1

1
self.transactions.group("user_id").select("user_id, sum(amount) as total_amount").order("sum(amount) DESC").includes(:user)

这修复了弃用警告并启用了急切加载。感谢 Rails 4。:)

于 2014-09-01T13:59:22.660 回答