前提・実現したいこと
バックエンドにRails
、フロントエンドにVue
を使用してユーザ登録ページを作成するということを行なっています。
ページの読み込みにはTurbolinks
を用いているため、Vueのプラグインvue-turbolinks
を用いています.
発生している問題・エラーメッセージ
ユーザ登録ページでフォームに対して情報を入力し、送信した後に別のページへと
リダイレクトさせようとしているが、リダイレクトされない。
該当のソースコード
user_controller.rb
ruby
1# coding: utf-8 2class UsersController < ApplicationController 3 4 def new 5 @user = User.new 6 end 7 8 def create 9 @user = User.new(user_params) 10 if @user.save 11 flash[:success] = "ユーザを登録しました。" 12 redirect_to '/' 13 else 14 flash[:danger] = "入力エラーです。" 15 redirect_to '/signup' 16 end 17 end 18 19 private 20 def user_params 21 params.require(:user).permit(:user_name, :email, :password, :password_confirmation) 22 end
new.html.erb
ruby
1<h1>Add</h1> 2</div> 3<%= javascript_pack_tag 'new' %> 4<div>
new.vue
vue
1<template> 2 <form accept-charset="UTF-8"> 3 <input type="text" v-model="username" placeholder="username"> 4 <input type="text" v-model="email" placeholder="email"> 5 <input type="password" v-model="password" placeholder="password"> 6 <input type="password" v-model="password_confirm" placeholder="password(confirm)"> 7 <button type="submit" v-on:click="sendForm">send</button> 8 </form> 9</template> 10 11<script> 12import axios from 'axios'; 13 14const token = document.getElementsByName("csrf-token")[0].getAttribute("content"); 15axios.defaults.headers.common["X-CSRF-Token"] = token; 16axios.defaults.headers.common["Content-Type"] = "application/json"; 17axios.defaults.headers.common["charset"] = "utf-8"; 18axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"; 19 20export default { 21 data: function() { 22 return { 23 username: "", 24 email: "", 25 password: "", 26 password_confirm: "" 27 } 28 }, 29 methods: { 30 sendForm: function(e){ 31 axios.post("/signup", { 32 "user": { 33 "user_name": this.username, 34 "email": this.email, 35 "password": this.password, 36 "password_confirmation": this.password_confirm, 37 } 38 }) 39 .then(response => { 40 }) 41 .catch(response => { 42 }); 43 } 44 } 45} 46</script>
new.js
import Vue from 'vue'; import New from '../new.vue'; import TurbolinksAdapter from 'vue-turbolinks'; Vue.use(TurbolinksAdapter); document.addEventListener('turbolinks:load', () => { const el = document.body.appendChild(document.createElement('new')); const new_ = new Vue({ el, render: h => h(New) }); console.log('/new page'); });
試したこと
axios.postによって受け取ったレスポンス内部にTurbolinksの関数が返ってきていたので
Functionクラスを用いて実行をすることによってリダイレクトは実現できたのですが
正しい方法ではないと思われます
補足情報(FW/ツールのバージョンなど)
Rails: 5.2.2
Ruby: 2.5.1
Turbolinks: 5
vue-turbolinks: 2.0.4
webpacker: 3.5
あなたの回答
tips
プレビュー