2014-11-08 182 views
0

我正在製作一個類似Instagram的克隆,其中用戶上傳得到投票的圖片。在範圍中使用自定義方法/重構自定義方法

我該如何重構這段代碼? 如何通過減少百分比來默認範圍?

class Picture < ActiveRecord::Base 
    mount_uploader :picture, PictureUploader 
    has_and_belongs_to_many :tags 
    has_many :votes, :dependent => :destroy 

    def vote_count 
     return self.votes.count 
    end 

    def up_votes 
     return self.votes.where('up like ?', true).count.to_f 
    end 

    def down_votes 
     return self.votes.where('up like ?', false).count.to_f 
    end 

    def percent 
     return self.up_votes/self.vote_count 
    end 

end 

FYI我的投票模型只跟蹤畫面和用戶ID,並擁有高達:布爾,:默認=>假

這一切都似乎比它可能是不夠簡明,你會如何寫這更好的?

回答

0
class Picture < ActiveRecord::Base 
    mount_uploader :picture, PictureUploader 
    has_and_belongs_to_many :tags 
    has_many :votes, :dependent => :destroy 

    def vote_count 
     return self.votes.count 
    end 

    def votes_status(status) 
     return self.votes.where('up like ?', status).count.to_f 
    end 

    def percent 
     return self.votes_status(true)/self.vote_count 
    end 

end 
+0

好的謝謝。範圍如何? – 2014-11-08 05:45:37

+0

您可以在範圍內移動這些方法,例如: 範圍:votes_status,lambda {| status = false | self.votes.where('up like?',status).count.to_f } – Thorin 2014-11-08 05:53:35