【问题标题】:Devise current_user Form Submission "User can't be blank"设计 current_user 表单提交“用户不能为空”
【发布时间】:2017-02-13 09:50:42
【问题描述】:

我的课程控制器中有一个简单的创建操作。我正在使用 current_user.built 命令来创建对象

courses_controller.rb

class CoursesController < ApplicationController
  before_action :authenticate_user!, expect: [:index, :show] 
  before_action :set_course, only: [:show, :edit, :update, :destroy]


  # GET /courses/new
  def new
    @course = current_user.courses.build
  end





  # POST /courses
  # POST /courses.json
  def create
    @course = current_user.courses.build(course_params)
    respond_to do |format|
      if @course.save
        format.html { redirect_to @course, notice: 'Course was successfully created.' }
        format.json { render :show, status: :created, location: @course }
      else
        format.html { render :new }
        format.json { render json: @course.errors, status: :unprocessable_entity }
      end
    end
  end





  private
    # Use callbacks to share common setup or constraints between actions.
    def set_course
      @course = Course.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def course_params
      params.require(:course).permit(:name, :description, :user_id)
    end
end

在浏览器中创建新课程时出现以下错误:

1 个错误禁止保存此课程: 用户不能为空

这是表单视图:

<%= form_for(@course) do |f| %>
  <% if @course.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@course.errors.count, "error") %> prohibited this course from being saved:</h2>

      <ul>
      <% @course.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

有什么想法可能是这里的问题吗? Devise 和 current_user 方法在控制台和其他模型上运行良好

【问题讨论】:

    标签: ruby-on-rails ruby authentication devise


    【解决方案1】:

    在您的控制器中,方法 course_params 不应允许在参数中传递 user_id,除非您希望用户为其他用户创建课程。因为您是从 current_user 构建课程,所以不需要它。

    还要检查您的课程模型是否验证了用户的存在,而不是 user_id。

    【讨论】:

    • 感谢您的回答。这是用户和课程之间的一种习惯关系,这就是我需要传入 user_id 的原因。但是您关于 :user 而不是 :user_id 的验证的提示起到了作用。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-05-13
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多