【问题标题】:Updating Mongoid document in Rails 4 rake task在 Rails 4 rake 任务中更新 Mongoid 文档
【发布时间】:2014-06-17 17:38:14
【问题描述】:

在我升级到 Rails 4 之前,这段代码似乎运行良好:

desc "import the books"
task books: :environment do
  records = JSON.parse(File.read('app/data/books.json'))
  records.each do |record|
    book = Book.find_or_create_by(:link => record["link"])
    record.each do |k, v|
      if book.send(k).blank?
        book.send(k+"=", v)
      else
        unless v.blank?
          book.send(k+"=", v)
        end
      end
    end
    book.save
  end
end

但是现在当我尝试导入它时,所有值(除了 find_or_create_by 方法中指定的 :link 之外)都是 nil。

#<Course _id: 53a07c1f4d61630d34980200, name: nil, language: nil, image: nil, link: "example.com", affiliate_link: nil>

这是由 Rails 4 中实现的某种针对批量分配的保护引起的吗?我没有意识到这可能会影响 Rake 任务。我怎样才能最好地解决这个问题。感谢您的快速帮助!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 mongoid rake


    【解决方案1】:

    find_or_create_by 由于某种原因无法正常工作,因此我实施了以下解决方法:

    book = Book.where(:link => record["link"]).first
    if book.blank?
      book = Book.create!
    end
    

    这似乎具有完全相同的效果,但实际上在 Rails 4 / Mongoid 4.0.0.beta1 中有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-23
      相关资源
      最近更新 更多