How to get and add data from Firebase Firestore in Ruby

Get and add data from Firestore in Ruby

This time, I will summarize the code that issues a query when retrieving data from Firestore in Ruby and the code that adds data.

What is Firestore

A NoSQL cloud database provided by Firebase.

the term

For the time being, I think it's okay if you know the following three terms in Firestore.

Cloud Firestore data model

collection

A general frame for storing data (documents). If you click on Cloud Firestore in the sidebar of the Firebase console, the collection will be on the far left of the screen. Data (documents) related to it are stored in one collection.

document

Data stored in the collection. The data is managed by a unique document ID, and there is a field associated with that document ID.

field

Data associated with one document. It is possible to link multiple documents to one document.

The above nested structure is the Firestore data model. So, "getting the values from the collection to the document and in the fields" is the act of getting the Firestore data. I get the impression that you have to take quite a few steps.

The methods described below need to be able to use Firestore methods.

Make firebase work with Rails

Instead of using ActiveRecord, which is an ORM of mysql, it works with a gem for accessing data in the fiestore.

Make firesotre available

There is a gem that allows you to use the firestore

gem 'google-cloud-firestore'

Is used.

Create a Firestore object

Firestore settings

About class_attribute

firebase.rb


class Firesbase
  require 'google/cloud'

  class_attribute :connecting
  self.connecting = Google::Cloud.new(Project name created in the console).firestore
end

Specify a collection

First, determine from which collection you want to get the data. If you use the collection method and specify the collection name created on the Firebase console as an argument, you can use the method to get data for that collection.

collection.rb


  hogehfuges_colleciton = connecting.collection 'hogefugas'

Get the data

It seems that the following three are used as the main methods for acquisition.

document

get_by_document.rb


  hoge = hoge_collection.document(Document ID).get      #Google::Cloud::Firestore::DocumentSnapshot
  fuge = fuge_collection.document(Document ID).get.data # Hash

By taking the document ID as an argument, document gets the data associated with the document ID. If you use the get method, you can get it with an object called Google :: Cloud :: Firestore :: DocumentSnapshot, but since you can not handle the data of the field inside as it is, use the data method. If you use the data method, it will make a hash with the field associated with the acquired document as a key, and you can easily access the data by the hash operation as shown below.

data.rb


  fuge[:fugefuge_name]

where where gets the one that meets the condition. In the case of where, if you use the get method, the object type will be Enumerator, so you need to use loop processing or a method that includes loop processing in the Ruby standard library (for example, map). You can use the data method on the data retrieved in a loop so that you can access the data.

get_by_where.rb


  snap = hogefugas_collection.where(conditions).get #Enumerator
  snap.map do |hoge|
    {
      "hoge_name" => hoge.data[:hoge_name],
      "update_at" => hoge.data[:update_at]
    }
  end

order order specifies a field as an argument and gets the document in which the field exists. If order also goes through the get method, the object type will be Enumrator, so loop it before accessing the data. The code below uses the document_id method instead of the data method. This allows you to get the document ID of the document, not the field.

get_by_oder.rb


  hoges = hogefugas_collection.order('updatedAt').get.map { |hoge| hoge.document_id }

Add data

Use the set method. Create data by using the field you want to save as the hash key. If you use it as an argument of the set method, the document ID will be automatically generated in the specified collection and saved in the Firestore.

set.rb


def save(id, hoge)
    huge = {
      id: id,
      hogehoge: hoge,
      update_at: DateTime.now.strftime("%Y-%m-%d-%H:%M")
    }
    collection.doc.set(huge)
  end

Update data

Use the update method. You can update the data by specifying the document ID in the collection you want to update and using that field as an argument of the update method.

update.rb


  def edit(id, hoge)
    document_id = collection.where("id", "=", id).get.first.document_id
    collection.document(document_id).update(
      hogehoge: hoge,
      update_at: DateTime.now.strftime("%Y-%m-%d-%H:%M")
    )
  end

Recommended Posts

How to get and add data from Firebase Firestore in Ruby
How to get date data in Ruby
[IOS] How to get data from DynamoDB
How to overwrite Firebase data in Swift
[Ruby] How to convert from lowercase to uppercase and from uppercase to lowercase
How to get Class from Element in Java
How to handle TSV files and CSV files in Ruby
[Ruby] How to get the tens place and the ones place
[IOS14] How to get Data type image data directly from PHPickerViewController?
How to iterate infinitely in Ruby
How to get parameters in Spark
How to install Bootstrap in Ruby
[Ruby On Rails] How to search and save the data of the parent table from the child table
How to delete large amounts of data in Rails and concerns
[Java] How to convert from String to Path type and get the path
[Java] How to add data to List (add, addAll)
How to add jar file in ScalaIDE
How to get the date in java
[Easy] How to upgrade Ruby and bundler
I tried to create an API to get data from a spreadsheet in Ruby (with service account)
How to change the maximum and maximum number of POST data in Spark
Try to get data from database using MyBatis in Micronaut + Kotlin project
How to get the setting value (property value) from the database in Spring Framework
How to create your own annotation in Java and get the value
How to get keycloak credentials in interceptor class
How to add / remove Ruby on Rails columns
[Java] How to get and output standard input
How to add sound in the app (swift)
How to add a classpath in Spring Boot
How to conditionally add html.erb class in Rails
How to get and study java SE8 Gold
How to get SIMD optimization from HotSpot JavaVM
[Ruby on Rails] How to install Bootstrap in Rails
[Rails] How to get success and error messages
How to build the simplest blockchain in Ruby
[ruby] How to receive values from standard input?
Ruby How to convert between uppercase and lowercase
How to implement Pagination in GraphQL (for ruby)
I want to get the value in Ruby
[JPA] Compare table1 and table2 to get and update data that does not exist in table2.
[Ruby] Learn how to use odd? Even? And count the even and odd numbers in the array!
How to get the ID of a user authenticated with Firebase in Swift
How to start a subscript from an arbitrary number in Ruby iterative processing
How to clear all data in a particular table
[Ruby] How to use standard output in conditional branching
[Ruby] Summary of how to get values from standard input [Paiza skill check measures]
[Ruby on Rails] How to write enum in Japanese
Rails / Ruby: How to get HTML text for Mail
How to get information about associated tables in many-to-many tables
[Java] How to get the key and value stored in Map by iterative processing
How to create a data URI (base64) in Java
[Ruby On Rails] How to reset DB in Heroku
How to launch another command in a Ruby program
How to store Rakuten API data in a table
From Java to Ruby !!
How to convert A to a and a to A using AND and OR in Java
[Swift] How to get the document ID of Firebase
(Ruby on Rails6) How to create models and tables
[Kotlin] How to get IP address and user agent
How to launch Swagger UI and Swagger Editor in Docker
How to resolve SSL_connect error in PayPal Ruby SDK