Ruby on rails 更新资源未定义方法“有效”和#x27;对于false:FalseClass
我对我的课程模型进行了一些验证,并且我能够使用Ruby on rails 更新资源未定义方法“有效”和#x27;对于false:FalseClass,ruby-on-rails,validation,controller,Ruby On Rails,Validation,Controller,我对我的课程模型进行了一些验证,并且我能够使用valid?方法在create操作下突出显示控制器上的验证问题。但是,如果我尝试以类似的方式valid?,我会得到undefined methodvalid?”for false:FalseClass`如何在提交时验证我的编辑表单,以便在验证未通过时再次呈现编辑表单 课程模式: class Lesson < ActiveRecord::Base belongs_to :user has_many :words, dependent: :
valid?
方法在create操作下突出显示控制器上的验证问题。但是,如果我尝试以类似的方式valid?
,我会得到undefined method
valid?”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
班主任::LessonsController
如果您看到一个错误,该错误看起来像“false:false类”的未定义方法“valid”
这意味着,无论在哪里调用方法:valid?
,调用它的对象都不是您期望的对象,而是false
因此,在代码中有两个实例调用@lesson.valid?
,这意味着@lesson
的一个或两个赋值有时返回false
在中,它表示:无论对象是否成功保存到数据库,都会返回结果对象。
在中,它说:如果对象无效,保存将失败并返回false。
因此,您的问题似乎是update\u attributes
,如果更新失败,它显然只返回false