Я конвертирую свой интерфейс из рельсов в Vue.JS, но немного запутался, как ввести user_id current_user в форму Vue.JS и передать его обратно в мой рельс.Как я могу передать user_id, чтобы, когда моя форма Vue.JS отправляла новую запись ... она отправляла user_id 'current_user' обратно в базу данных rails?
Просмотр новой записи (New.html.erb)
<%= content_tag :div, id: "new-post", data: { id: @post.id, user_id: current_user.id } do %>
<label>Title:</label>
<input type="text" class="form-control" v-model="post.title">
<button v-on:click="SavePost" class="btn btn-info">Save Post</button>
Application.JS (VUE js)
import Vue from 'vue/dist/vue.esm'
import VueResource from 'vue-resource'
import TurbolinksAdapter from 'vue-turbolinks'
Vue.use(TurbolinksAdapter)
Vue.use(VueResource)
document.addEventListener("turbolinks:load", function() {
Vue.http.headers.common['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
var element = document.getElementById("new-post")
if (element != undefined) {
var id = element.dataset.id
var post = JSON.parse(element.dataset.post)
var app = new Vue({
el: element,
data: function() {
return {
post: post,
user: current_user
}
},
methods: {
SavePost: function() {
if(this.id == null) {
this.$http.post(url, { post: this.post }).then(response => {
Turbolinks.visit(`/posts/${response.data.id}`)
}, response => {
console.log(response)
if(response.status = 422) {
var json = JSON.parse(response.bodyText);
this.errors = json["post.title"][0]
}
})
}
},
}
})
}
});
Контроллер сообщений
class PostsController < SignedInController
before_action :authenticate_user!, except: [:create]
layout "signed_in"
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@user = current_user
end
respond_to do |format|
if @post.save
format.html { redirect_to root_path, notice: 'Post was successfully created.' }
format.json { render json: { id: @post.id}, status: :ok }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
# flash[:error] = @post.errors.full_messages.join(',')
# redirect_to new_post_path
end
end
def post_params
params.require(:post).permit(:title, :user_id)
end
end
Модель сообщения:
class Post < ApplicationRecord
# uncomment to make users be logged in to post Posts
belongs_to :user
end