使用first_or_create时,nilClass的未定义方法’+’

我有一个在记录上使用first_or_create的函数,我需要能够在它存在的情况下对其中一个属性使用+

 Blob.where(user_id: user.id, item_id: item.id).first_or_create do |s| s.amount += amount end 

但是,如果记录不存在,我不能使用+ 。 这是一个语法问题还是我使用first_or_create

只有在创建对象时才会调用该块(尚未找到一个)。 如果模型没有给定字段的默认值,它将尝试在nil值上调用+ 。 你可以沿着这些方向做一些事情(可能有更好的方式):

 blob = Blob.where(user_id: user.id, item_id: item.id).first_or_create blob.amount += amount if blob.amount.present? 

在这种情况下,只有在对象已经存在的情况下才会执行sum (根据您的描述,这似乎是您的目标)。 如果要在任何情况下应用金额总和,如果记录尚不存在,则可以将金额初始化为0

 blob = Blob.where(user_id: user.id, item_id: item.id).first_or_create do |b| b.amount = 0 end blob.amount += amount 

在上面的示例中,如果存在对象,则它将向当前值添加amount ,否则它将使用0初始化该属性,然后向其添加amount

对s.amount执行空检查。 如果之前不存在,则s.amount将为nil ,这自然不能添加到。

您可以使用以下方法执行此操作。

 Blob.where(user_id: user.id, item_id: item.id).first_or_create do |s| if s.amount.nil? s.amount = amount else s.amount += amount end end 

或者,您可以在该字段上设置default 0,但我对该字段不肯定。