简体   繁体   English

rails: nil:NilClass 的未定义方法`>'

[英]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:如果投票大于 0,我需要比较投票。我得到错误:“undefined method `>' for nil:NilClass”,代码如下:

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.但是通常,如果您得到 nils,则表明您应该在列上使用默认值,或者应该在加载数据的数据库查询中使用 COALESCE。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM