Ziga Zupanc
Ziga Zupanc

Reputation: 13

rails: undefined method `>' for nil:NilClass

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

Upvotes: 0

Views: 147

Answers (2)

max
max

Reputation: 101811

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'
)

Upvotes: 3

Ziga Zupanc
Ziga Zupanc

Reputation: 13

The anwser was:

  if self.upvotes && (self.upvotes > 0) || self.downvotes && (self.downvotes > 0)
    self.upvotes > 0 ? (self.upvotes - self.downvotes) : (self.downvotes * -1)

Upvotes: 0

Related Questions