我正在创建一个类似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
仅供参考我的投票模型只跟踪图片和用户ID并且有向上:boolean,:default =&gt;假
这一切看起来都不那么简洁,你会怎么写得更好?
答案 0 :(得分: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