LoginSignup
11
16

More than 3 years have passed since last update.

【Rails】RailsでDBからデータを読み込み、Vue.jsを通じてブラウザに出力する方法

Posted at

はじめに

RailsでDBからデータを読み込み、Vue.jsを通じてブラウザに出力する方法についてまとめました。

今回はusers_controllerindexアクションで取得された情報をVue.jsで表示する方法を例にしています。

環境

OS: macOS Catalina 10.15.1
Ruby: 2.6.5
Rails: 6.0.2.1
Vue: 2.6.10
vue-cli: 4.1.1
axios: 0.19.0

前提

nameemailの2つのカラムを持つUserモデルをRailsで作成済とし、その情報をVue.jsで表にして表示するプログラムを例にします。

また、axiosはインストール済とします。
※インストール方法はこちらの公式ドキュメントを参照。

1.Rails側

1-1.users_controller

ディレクトリを新規作成・移動

通常:app/controllers/

変更後:app/controllers/api/v1/
 ※api/v1/は新規ディレクトリ作成

classにApi::V1::を書き足す

app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < ApplicationController

indexアクションの定義を変更

app/controllers/api/v1/users_controller.rb

...
  def index
    #Vue.js側で呼び出したいデータだけをselectで抜き出す
    users = User.select(:id, :name, :email)
    #JSON形式でusersを出力 
    render json: users
  end
...
end

1-2.routes.rb

ルーティングも上記に沿って書き換えます。
通常のRailsアプリと違って、namespaceで囲う必要があります。

routes.rb
Rails.application.routes.draw do
...
  namespace :api, {format: 'json'} do
    namespace :v1 do
      resources :users, only: [:index]
    end
  end
end

これで、開発環境なら

localhost:3000/api/v1/users

にアクセスすると、

users_controllerindexアクション

が発動し、

JSON形式でUserモデルのid, name, email

が出力出来る状態になりました。
あとはこのデータをVue.js側で拾います

2.Vue.js側

UsersIndex.vueという単一ファイルコンポーネントでデータを表示することにします。

※単一ファイルコンポーネントをどう読み込んでブラウザに表示するかについては割愛させて頂きます。

UsersIndex.vue
<template>
  <table>
    <tbody>
      <tr>
        <th>ID</th>
        <th>name</th>
        <th>email</th>
      </tr>
      <tr v-for="user in users" :key="user.id">
        <td>{{ user.id }}</td>
        <td>{{ user.name }}</td>
        <td>{{ user.email }}</td>
      </tr>
    </tbody>
  </table>
</template>

<script>
// axiosを読み込む
import axios from 'axios';

export default {
  data() {
    return {
      //axiosで取得するデータを入れるため、空でOK
      users: []
    }
  },
  //mountedでVueインスタンスのDOM作成完了直後に読み込む
  mounted() {
    axios
      //GETリクエストでRailsで作成したjsonを取得する
      .get('/api/v1/users.json')
      //response.data は RailsのUser.select(:id, :name, :email)
      //これをdata()で定義したusersに代入する
      .then(response => (this.users = response.data))
  }
}

</script>

これでJSON形式だったUserモデルのid, name, emailがVue.jsを通じてブラウザに表示出来ます。

以上です!

おわりに

最後まで読んで頂きありがとうございました:bow_tone1:

どなたかの参考になれば幸いです:relaxed:

参考にさせて頂いたサイト(いつもありがとうございます)

11
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
16