Rails + Firebase

How to use/setup Firebase on a Rails project.

Federicorudolf
2 min readJan 2, 2023

Why do that? Just to see if we can (spoiler alert, we can 😉). Obviously, most of the times we wouldn’t create a Rails project just for the frontend perks (in that case we could use Svelte, highly recommend it, or any other frontend framework). With a Rails project usually we commit to develop the entire app structure and wouldn’t rely on solutions like Firebase. In spite of that, Firebase is gaining a lot of popularity thanks to the many tools that it offers, the ease of usage, and the fact that it’s one of the best free options to start a project with (check on quotas and prices here).

Because of what I mentioned before, we could want to mix things up and use a couple of tools offered by Firebase in a Rails project, and below are the steps to do so, using two different approaches:

The gem way

  • Setup Firebase account & project
  • Create new Rails project / open existing one
  • Add Firebase gem to project (google cloud gem)
    — Open Google Console
    — Open `console.cloud.google.com`
    — Go to Service Accounts → Create service account & name it → Actions / Manage Keys → Add key → Create Key → JSON
    — Download it previous key
    — Move that file into your project’s root (⚠️ remember to add this file to your .gitignore file, so you don’t commit it into your repo ⚠️)
    — Add new line to credentials file: keyfile: PATH_TO_FILE/filename.json
    — Add gem google-cloud-firestore to Gemfile (* the gem name corresponds to each of the Firebase product suite, so we would need to provide the wanted ones, i.e: Authentication, Cloud Firestore, Cloud Functions, Hosting, etc)
    bundle install
  • Inside your controller, import the gem: require ‘google/cloud/firestore’ or require ‘google/cloud/authenticate’etc
  • We can use the gem by calling Google::Cloud::Firestore.new project_id: YOUR_PROJECT_ID, keyfile: Rails.application.credentials.keyfile

This last method returns a new Firestore object we can then use to call for the proper methods, such as collection(‘collection_name’).add() or collection('collection_name').delete() etc. and that’s it. To check all the methods provided by each module check the official docs here.

The HTTP way

We can avoid some of the previous steps by hard connecting to the Firebase API:

Make sure to check the official Firebase Docs for the REST way of connecting to the services.

Hope this was useful!

Thanks for reading.

--

--