簡體   English   中英

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

[英]rails: undefined method `>' for nil:NilClass

如果投票大於 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
    ....

使用算術有一個更簡單的解決方案:

def score
  (upvotes || 0) - (downvotes || 0)
end

但是通常,如果您得到 nils,則表明您應該在列上使用默認值,或者應該在加載數據的數據庫查詢中使用 COALESCE。

User.select(
  '*', 
  'COALESCE(users.upvotes, 0) - COALESCE(users.downvotes, 0) AS score'
)

答案是:

  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-2025 STACKOOM.COM