Rails如果存在更新,则使用find_or_create_by创建

时间:2012-12-14 00:06:14

标签: ruby-on-rails ruby-on-rails-3 postgresql

我正在尝试运行一种方法,如果存在(表Hashtag列标记)标记,它会将视图计数更新为1.否则它将创建一个新行,其默认视图计数为0,并且@hashtag标记已擦除

Hashlog.rb

def self.create_hashlog(hashtag)        #enters hashtag into the log table, without #. 
        @hashtag_scrubbed = hashtag
        # Hashlog.find_or_create_by_tag(@hashtag_scrubbed) 

        taglog = Hashlog.find_or_create_by_tag(@hashtag_scrubbed) do |t|
        t.count = 0
        end
        taglog.count += 1
        taglog.save!    
    end

错误

Completed 500 Internal Server Error in 772ms

NoMethodError (undefined method `+' for nil:NilClass):
  app/models/hashlog.rb:24:in `create_hashlog'
  app/controllers/hashtags_controller.rb:32:in `create'

2 个答案:

答案 0 :(得分:0)

如果您的查找失败(因为没有记录)并且您的创建失败(因为验证失败),则函数返回nil。

答案 1 :(得分:0)

将其更改为find_or_initialize_by_tag解决了它 - stephenmurdoch