Creating an app with Rails API backend VueJS frontend.

Simon Cooper
May 8, 2018 · 7 min read

Your Rails App

$ rails new sandbox --api -d postgresql
/sandbox/config/initializers/cors.rbRails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'

resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possiblegem 'rack-cors'
$ bundle install
$ rails db:create
$ rails generate scaffold Contacts name:string relationship:string
class CreateContacts < ActiveRecord::Migration[5.2]
def change
create_table :contacts do |t|
t.string :name
t.string :relationship
t.timestamps
end
end
end
$ rails db:migrate
/sandbox/config/routes.rbRails.Application.routes.draw do
resources: contacts
end
render json: @contacts
$ rails console
2.4.0 :001 > Contact.create!(name: 'Simon', relationship: 'me')
$ rails server

Your VueJS App

$ npm install -g vue-cli
$ vue init webpack sandboxfront #or whatever name you wish 
$ npm run dev
$ npm install vue-router
import Vue from 'vue'
import Router from 'vue-router'
import Contacts from '@/components/Contacts' #add this line
Vue.use(Router)export default new Router ({
routes: [
{
path: '/',
name: 'HelloWorld',
component: 'HelloWorld'
},
{ #add these lines
path: '/contacts',
name: 'Contacts',
component: 'Contacts'
}
]
})
<template>
<div id="contacts">
<div v-for="(contact, index) in contacts" :key="contact.id">
<p>{{contact.name}} is my {{contact.relationship}}</p>
</div>
</div>
</template>
$ npm install axios
<script>
import axios from 'axios'
export default {
data() {
return {
contacts: [],
name: [],
relationship: [],
errors: []
}
},
created() {
axios.get('localhost:3000/contacts')
.then(response => {
.this.contacts = response.data
})
.catch(e => {
this.error.push(e)
})
},
}
</script>

Simon Cooper

Written by

Photographer. Hobbyist Developer. Digital Marketer. Fan of beards. Live in East London.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade