首页 > 解决方案 > update_columns 更新一个字符串,但在 Rails 上获取时它是 nil

问题描述

我正在尝试将文件保存到 Google Storage 存储桶,我遵循了 rails 的官方指南

所以我有这个代码来更新我的文件

after_create :upload_document, if: :path 

  def upload_document
    file = Document.storage_bucket.create_file \
      path.tempfile,
      "cover_images/#{id}/#{path.original_filename}",
      content_type: path.content_type,
      acl: "public"
    # Update the url to my path field on my database
    update_columns(path: file.public_url)
  end

我可以将我的文件存储在我的存储桶中,我可以检索public_url并更新我表上的路径字段,但是当我尝试获取路径字符串时,我有一个nil. 我的 Rails 控制台上的示例

Document.find(14) 
=> #<Document id: 14, name: "Test", path: "https://storage.googleapis.com/xxxxxxxx-xxxx.x...", created_at: "2018-10-05 07:17:59", updated_at: "2018-10-05 07:17:59">
Document.find(14).path
=> nil
Document.find(14).name
=> "Test"

所以我不明白为什么我可以在使用Rails的update_columns更新后访问我的 SQL 数据库上的路径字段。

非常感谢你的帮助

标签: ruby-on-railsrubyruby-on-rails-4google-cloud-storage

解决方案


Document您在覆盖默认属性访问器的类(或包含的模块)上定义了一些方法。

要找出哪个,请在控制台中编写:

Document.find(14).method(:path).source_location

在任何情况下,您都可以直接访问该属性

Document.find(14)['path']

推荐阅读