使用Rails和Vue.JS将Devise用户ID传递到Post模型

时间:2018-12-02 19:24:06

标签: ruby-on-rails vue.js devise ruby-on-rails-5 vue-component

我正在将前端从Rails转换为Vue.JS,但对于如何将current_user的user_id引入Vue.JS表单并将其传递回Rails后端感到有些困惑。如何传递user_id,以便当我的Vue.JS表单提交新的Post ...时,它将“ current_user”的user_id发送回rails DB?

新帖子视图(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

1 个答案:

答案 0 :(得分:1)

如果始终为post创建一个current_user,则无需在view / Vue内部传递任何user_id并让控制器执行此操作:

def create
  @post = Post.new(post_params)
  @post.user = current_user

  respond_to do |format|
    #...
  end
end