如何使用Ruby连接到Firestore数据库

时间:2019-07-18 18:55:44

标签: ruby google-cloud-firestore

我正在尝试通过Ruby脚本(最终是从Rails应用程序)来读写Firestore数据库。

这似乎是一项琐碎的任务,但是当我在IRB中运行测试脚本时,它不会让我写入或读取数据。

我尝试过:

  • 已成功安装google-cloud-firestore gem
  • 从Firestore控制台中下载JSON密钥文件。
  • 将安全规则设置为公共(读和写)
require 'google/cloud/firestore' # => true

# credentials
cred = Google::Cloud::Firestore::Credentials.new('<path/to/my/keyfile/key-projectname-etc.json>') 
# => #<Google::Cloud::Firestore::Credentials:...>

# initialize firestore connection
db = Google::Cloud::Firestore.new(
  project_id: '<MY-PROJECT-ID>',
  credentials: cred
) # => #<Google::Cloud::Firestore::Client:...>

# write a document inside the users collection
db.doc("users/helloFromRuby").set({ name: "yay it worked!"})

这是我收到的错误消息:

Google::Cloud::UnavailableError (14:failed to connect to all addresses)

1 个答案:

答案 0 :(得分:1)

我可以解决我的问题:我初始化了一个环境变量GOOGLE_APPLICATION_CREDENTIALS,以某种方式干扰了我的json密钥文件。删除该变量解决了我的问题。