简体   繁体   中英

Connecting my Rails Web app database to my Rails API on Heroku

I feel like my question is partially answered through a number of other questions, but I just can't piece everything together for my case.

Basically, I'd like to build a fairly simple web app, but also be able to fairly easily build a mobile app for it down the line. From my research, the best practice would be to build a RESTful JSON API, and then use that API both for my web app and for my mobile app.

I've already gone ahead and developed authentication for my JSON API (using : http://lucatironi.net/tutorial/2015/08/23/rails_api_authentication_warden/ ) and I've got it up on Heroku. Now for my web app, I'm using HTTParty to consume that API, and I'm getting the JSON back all fine and dandy. However, I'm not quite so sure what to do with the database. My first thought was that maybe I need to access the API's database via it's own API calls, but that seems incredibly complex (just the thought of having to make functions for User.find_by_<every attribute> makes me scared). The other thought would be to have my web app use the API app's database. However, I can't find any info on how to do that if the app is on Heroku.

So basically, I'm wondering what the best way to go about this would be. Surely there is a standard out there that every big or small web app with an API uses. I'm really surprised that something so prevalent these days is hard to find good answers for. Or am I going about this all wrong? Any pointers would be greatly appreciated.

Databases are add-ons in Heroku parlance.

Use heroku addons to get a list of the add-ons for your apps.

$ heroku addons -a appname

Add-on                                    Plan       Price
────────────────────────────────────────  ─────────  ─────
heroku-postgresql (relaxing-purely-8366)  hobby-dev  free 
 └─ as DATABASE    

First you may want to remove the database attached to your front-end app:

heroku addons:destroy fat-samurai-1234

Then find the name of the database add-on attached to your API app and attach the add-on to your frontend app.

heroku addons:attach shining-sushi-1234 -a sushi.

As to which approach is legitimate that's a matter of discussion. Many apps today use a single page architecture where the entire app is created on the front end - in javascript. So your app just consumes your REST api. Popular frameworks for this are Ember.js, Bootstrap and Angular.

The other approach would be to to create a classic server side app - while it's possible to create an app that would consume the REST api there is a significant overhead involved so it will be more performant to connect directly to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM