How to Add Vue to a Rails 5.1 App

  • rails, vue.js

Rails 5.1 makes it really easy to use JavaScript libraries such as Vue. The latest version of Rails provides Yarn support so JS dependencies play nice with the assets pipeline. I haven't seen too many resources for creating a new Rails project with Vue, so here is how I did it.

  1. Update Rails with gem install rails -v 5.1
  2. I didn't have Node.js installed, so I had to install that next (you might not need to):
  3. Install Yarn: . I used Homebrew. I had to update it first with brew update and then I was able to run brew install yarn
  4. Run rails new with the webpack vue flag: rails new my_app --webpack=vue .
  5. If you haven't already, run rails db:create and rails db:migrate and fire up Rails server to make sure everything is up and running.
  6. In the file structure, you'll notice a hello_vue.js file in app/javascript/packs. At the top of the file, there are commented-out instructions for adding <%= javascript_pack_tag 'hello_vue' %> to the <head> of app/views/layouts/application.html.erb. Do that now.
  7. Create a controller. I used rails g controller Teams and in the controller add an index action:
class TeamsController < ApplicationController
  def index

Add routes:

Rails.application.routes.draw do
  resources :teams

In config/environments/development.rb, add config.x.webpacker[:dev_server_host] = "" This will enable javascript_pack_tag to load assets from the webpack dev server.

Run the webpack server on another port: ./bin/webpack-dev-server --host

Create index.html.erb in views/teams and navigate to http://localhost:3000/teams. If you see the "Hello Vue", you are good to go.