Search code examples
ruby-on-railsrubyember.jsember-clidevelopment-environment

How to Connect an Ember app to a Rails API?


Currently having some trouble understanding how to connect an Ember app to a Rails API in my local dev environment. I'm pretty unfamiliar with this sort of set up, as opposed to just running a purely Rails application.

So run when I'm running these two separate apps, it looks like:

Ember app running on `localhost:4200`
Rails API running on `localhost:3000`

And both applications are in the same directory

Parent Directory
|
|___ API
|
|___ Ember App

When I visit both localhost URLs, both the apps are running. The Rails API seems to be fine, but the Ember app displays the default "There's something wrong" page that was made, and below is the error I receive in the console:

enter image description here

I was hoping someone could explain what might be wrong with my set up, that's causing this error.


Solution

  • Since you have not posted any files here it how it should be setup

    Inside Ember define application adapter that has namespace property:

    export default ActiveModelAdapter.extend({
      namespace: 'api'
    });
    

    Inside rails config/routes.rb you should have something like this:

    namespace :api, defaults: {format: 'json'} do
      resource :companies
    end
    

    This resource should be defined inside app/api/companies_controller.rb

    module Api
      class CompaniesController < ActionController::Base 
        skip_before_action :verify_authenticity_token
    
        def index
        ...
      end
    end
    

    Once you do this you can start environment like this:

    ember server --proxy http://localhost:3000

    Note that this is defined by routes not location inside directories. Proxy is also important if it is served separately.

    You can check this add-on that helps merge two:

    https://github.com/thoughtbot/ember-cli-rails

    Hope it helps.