【问题标题】:Pass Devise User ID to Post model using Rails and Vue.JS使用 Rails 和 Vue.JS 将设计用户 ID 传递给 Post 模型
【发布时间】:2018-12-02 19:24:06
【问题描述】:

我正在将我的前端从 rails 转换为 Vue.JS,但对于如何将 current_user 的 user_id 引入 Vue.JS 表单并将其传递回我的 rails 后端有点困惑。如何传递 user_id 以便当我的 Vue.JS 表单提交新帖子时...它将“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

【问题讨论】:

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


    【解决方案1】:

    如果始终为current_user 创建post,则无需在视图/Vue 中传递任何user_id 并让控制器完成工作:

    def create
      @post = Post.new(post_params)
      @post.user = current_user
    
      respond_to do |format|
        #...
      end
    end
    

    【讨论】:

    • 哇...好吧,不知道为什么我什至认为我需要将它传递给 Vue 并返回。感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多