I need to compare votes if they are greater than 0. And i get error: "undefined method `>' for nil:NilClass" with this code:
def score
if self.upvotes > 0 || self.downvotes > 0
self.upvotes > 0 ? (self.upvotes - self.downvotes) : (self.downvotes * -1)
else
....
There is a much simpler solution using arithmetic:
def score
(upvotes || 0) - (downvotes || 0)
end
But usually if you are getting nils its a sign that you should have defaults on the columns or should be using COALESCE in the db query where you load the data.
User.select(
'*',
'COALESCE(users.upvotes, 0) - COALESCE(users.downvotes, 0) AS score'
)
The anwser was:
if self.upvotes && (self.upvotes > 0) || self.downvotes && (self.downvotes > 0)
self.upvotes > 0 ? (self.upvotes - self.downvotes) : (self.downvotes * -1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.