我对Lesson模型进行了一些验证,并且我能够使用valid?
方法在创建操作下突出显示控制器上的验证问题。但是,如果我以类似的方式尝试valid?
,我会undefined method
有效吗?“ for false:FalseClass`如何在提交时验证我的编辑表单,以便在验证未通过时再次呈现编辑表单?
课程模型:
class Lesson < ActiveRecord::Base
belongs_to :user
has_many :words, dependent: :destroy
validates :title, presence: true, length: { maximum: 55 }
validates :description, presence: true, length: { maximum: 500 }
validates :subject, presence: true, length: { maximum: 55 }
validates :difficulty, presence: true, numericality: { less_than_or_equal_to: 5 }
end
控制器:
class Teacher::LessonsController < ApplicationController
before_action :authenticate_user!
before_action :require_authorized_for_current_lesson, only: [:show, :edit, :update]
def show
@lesson = Lesson.find(params[:id])
end
def new
@lesson = Lesson.new
end
def edit
@lesson = Lesson.find(params[:id])
end
def create
@lesson = current_user.lessons.create(lesson_params)
if @lesson.valid?
redirect_to teacher_lesson_path(@lesson)
else
render :new, status: :unprocessable_entity
end
end
def update
@lesson = current_lesson.update_attributes(lesson_params)
if @lesson.valid?
redirect_to teacher_lesson_path(current_lesson)
else
render :edit, status: :unprocessable_entity
end
end
private
def require_authorized_for_current_lesson
if current_lesson.user != current_user
render text: "Unauthorized", status: :unauthorized
end
end
def current_lesson
@current_lesson ||= Lesson.find(params[:id])
end
def lesson_params
params.require(:lesson).permit(:title, :description, :subject, :difficulty)
end
end
答案 0 :(得分:3)
如果您看到的错误类似于undefined method 'valid?' for 'false:FalseClass
这意味着无论您何时调用方法:valid?
,您调用它的对象都不是您期望的对象,而只是false
因此,您在代码中有两个实例,您调用@lesson.valid?
,这意味着@lesson
的一个或两个分配有时会返回false。
在docs of create中,它说:The resulting object is returned whether the object was saved successfully to the database or not.
在docs of update_attributes中,它说:If the object is invalid, the saving will fail and false will be returned.
所以看起来您的问题出在update_attributes
,如果您的更新失败,显然只会返回false
。