2015-10-11 27 views
1

在我正在創建的Web應用程序中,我必須爲每個用戶計算一個分數。我目前正在用這種方式計算得分:在Ruby on Rails上總結屬性的最佳方式

class Opinion < ActiveRecord::Base 
    belongs_to :hero 
    def score_value 
    self.note * (self.end_date - self.start_date) 
    end 
end 

class User < ActiveRecord::Base 
    has_many :opinions 
    def update_score 
    self.score = 0 
    self.opinions.each { |opinion| self.score += opinion.score_value } 
    self.save 
    end 
end 

但我覺得這不是最好的辦法。有沒有更好的方法來做到這一點?

回答

1

好了,我可以建議使用所有的紅寶石功率#update_score

class User < ActiveRecord::Base 
    has_many :opinions 
    def update_score 
    self.score = self.opinions.map(&:score_value).inject(0, &:+) 
    self.save 
    end 
end 

你可以做的另一件事是一些計算移動到數據庫:

class User < ActiveRecord::Base 
    has_many :opinions 
    def update_score 
    self.score = opinions.pluck(:note, 'DATEDIFF(end_date, start_date)').map do |note, days| 
     note * days 
    end.inject(0, &:+) 
    self.save 
    end 
end 

這僅僅是一個性能改善,我不認爲它的優雅。

+0

謝謝你,我正在使用你的第一個解決方案:)。 –

0

有多項改進,你可以在這裏做,我會去的是

重新計算分數時,屬性變化

class Opinion 
    before_save :update_score 

    def update_score 
    return unless note_changed? || end_date_changed? || start_date_changed? 
    self.note * (self.end_date - self.start_date) 
    end 
end 

更新分數是如何在用戶模型計算

class User 
    def update_score 
    self.score = self.opinions.sum(:score) 
    end 
end 
相關問題