Building a Rails 5 & Ember.js app

Blog Logo

Alessio Fanelli

on
08 Jun 2017

read

Since I had some free time over the past couple of weeks I decided to give the new Rails 5 API-only features a try. This post is based on Jorge Bejar's guide but adapted for use with Ember and including some extras as how to fix Devise not working with Rails 5 and other issues.

Since Rails 5 isn't released officially yet we'll need to clone the GitHub repo and build our application from there:

git clone git://github.com/rails/rails.git

Now navigate to the rails folder and run the code below. Just running 'rails new' won't work since it'd load your local version and not the one you just cloned.

If you go take a look at the generated controllers you'll see they are super clean, being an API-only app means no more respond_to, #edit or #new. We now have to create a serializer for our team object:

bin/rails g serializer team name city championships

Now we can start the server and create a new object. We could install active_admin at this point to easily create entries but it's not worth the effort since it doesn't work out of the box; we'll use the curl command instead.

While we have the gemfile open, let's uncomment rack-cors as well since we'll need it later on and then run bundle install. You should now go to 'config/initializers/cors.rb' and set what domains are allowed to access your API; if you only want your Ember app to do that, set origins 'localhost:4200' and you'll be set. Don't forget to add your production host later on.

We can now create a user through Rails' console with

User.create!(email: "test@test.com", password: "testtest")

Now on to Ember.js. I usually have the API and the frontend separated in two different repos and deploy them on two different servers, this means that locally they'll run on two different addresses and it needs a bit of tweaking. The first thing to do is set the host depending on your environment; you can do that in config/environment.js by setting:

And then set it up in config/environment.js after the ENV declaration. We're gonna need to whitelist our APIs domains in the simple-auth setting and set what authorizer we're using (Devise in our case); after that, we're gonna have to setup the serverTokenEndpoint. Since I didn't need to login in local I've added the production host and called it a day, but you can set it dinamically for each environment just like we did for the api_host value earlier.

And you'll be set! Now we can add our teams model to the frontend and move on from there. If you want to get serious about Ember.js development, the Toptal blog has an awesome article about the 8 most common mistakes new Ember devs do, definitely worth the time! it's written by Balint Erdi, author of 'Rock and Roll with Ember.js', take a look at it!