Reputation: 648
I have some validations for my Lesson model, and I'm able to highlight validation problems on the controller under the create action with the valid?
method. However, if I try to valid?
in an analogous manner, I get undefined method
valid?' for false:FalseClass` How can I go about validating my edit form upon submission, such that it renders the edit form again if the validation doesn't pass?
Lesson model:
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
Controller:
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
Upvotes: 3
Views: 1049
Reputation: 10762
If you see an error that looks like undefined method 'valid?' for 'false:FalseClass
That means that wherever you call the method :valid?
, the object on which you are calling it is not the object you expect, it is instead just false
So you have two instances in your code where you are calling @lesson.valid?
, which means one or both of the assignments of @lesson
is sometimes returning false.
In the docs of create, it says: The resulting object is returned whether the object was saved successfully to the database or not.
In the docs of update_attributes, it says: If the object is invalid, the saving will fail and false will be returned.
So it looks like your problem is with update_attributes
, which apparently just returns false
if your update was unsuccessful.
Upvotes: 3