Creating an Ember and Rails app with a POST request for a side project
Creating an Ember and Rails app with a POST request for a side project
This post is a tutorial that will go through creating a simple app with ember js on the front-end and ruby on rails on the back-end.
I am working on a side project called Work Vibes and I am going to do tutorials of parts of creating the app as I go along.
Work Vibes is going to be a project management tool for software developers.
This tutorial will go through setting up the app and doing a POST request.
Firstly let’s check what versions we are using:
ruby -v
>ruby 2.5.1p57
rails -v
>Rails 5.2.1
Ember version: “2.14.1”
Let’s create a new Ember app:
ember new work-vibes-projects-frontend
cd work-vibes-projects-frontend
Let’s do:
ember serve
Let’s add code to the application.hbs file:
<div> Welcome to Work Vibes Front-end App! :) </div>
You should now see that when you load the webpage!
Now let’s add a users route to the file router.js:
//app/router.jsRouter.map(function() { this.route(‘users’);});
Now let’s add a users route:
ember generate route users
We now have a file called users.js and users.hbs
Let’s add the following code to application.hbs:
{{outlet}}
and add this code to users.hbs:
<div>Users page</div>
Let’s add a button to create a new user in users.hbs:
<button {{action “createUser” “Katie” “[email protected]”}}> Create a new user </button>
Let’s create the corresponding action in the route file that prints “Create user” with the following code:
//app/routes/users.jsexport default Route.extend({ actions: { createUser(name, email) { console.log("Create user"); } }});
When the button is clicked we should see Create user logged in the javascript console.
Now let’s add the post request:
//app/routes/users.jslet user = this.get(“store”).createRecord(“user”, { name: name, email: email});user.save();
I get an error when I click the button which says:
Uncaught TypeError: Cannot read property ‘create’ of undefined
We need to create a User model.
ember generate model user
Let’s add the info to the model:
//app/models/user.jsexport default DS.Model.extend({ name: DS.attr("string"), email: DS.attr("string")});
Now when we click the createUser button we get a 404 error which is what we expect because we haven’t written the back-end code yet.
Let’s create our rails api and write the backend!
cd ..
rails new work_vibes_projects_api — api
cd work_vibes_projects_api
Let’s open up the routes.rb file and add the following line:
Rails.application.routes.draw do resources :usersend
Let’s generate a users controller:
rails generate controller users
Let’s add the following code to the controller:
class UsersController < ApplicationController protect_from_forgery
# POST /users def create user = User.create!(user_params) if user.save render jsonapi: user else render jsonapi_errors: user.errors end end private def user_params # whitelist params params.require(:_jsonapi) .require(:data) .require(:attributes) .permit(:name, :email) endend
We will be using a gem called jsonapi-rails, let’s install it:
Add the following to your application’s Gemfile:
gem ‘jsonapi-rails’
And then execute:
bundle install
Now let’s try to run our ember app and rails app together add see what happens.
let’s run the following line in the front-end folder:
and run the following in the back-end folder:
rails server
Now when I click the CreateUser button I get a 400 error that says (Empty Content-Type).
The front-end is not sending the data in the correct format for jsonapi.
I need to add an Adapter and a Serializer on the front-end.
Let’s add an adapters folder and add the file applicaion.js
It should look like this:
//app/adapters/application.jsimport DS from "ember-data";export default DS.JSONAPIAdapter.extend({ host: "http://localhost:3000", dataType: "json"});
Let’s also add a serlializers folder and the file application.js with the following content:
// app/serializers/application.jsimport DS from “ember-data”;export default DS.JSONAPISerializer.extend({});
Now I’m getting the following error:
Response for preflight has invalid HTTP status code 404.
This is related to CORS.
Let’s create the file /initializers/cors.rb to have the following code:
Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins 'example.com'
resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] endend
And restart the server.
Now when I click the button I get a 500 error because we have no user model.
Let’s create a user model on the back-end.
rails generate model user name:string email:string
Let’s run:
rails db:migrate
Now I get a different 500 error.
We need a serializable folder on the back-end anyway, with the file serializable_user.rb
The file should have the following code:
class SerializableUser < JSONAPI::Serializable::Resource type 'users'
attributes :name, :emailend
After restarting the server and clicking the button to create a user I am now getting a 200 which means success.
Let’s check if the user was saved to the database by running:
rails console
and doing:
User.last
This shows the user that was saved in the database.
The next step would be to add two input boxes with the name and email fields and save them.
The next blog post will show how to do a simple relationship between two models with ember and rails.