i have validations lesson model, , i'm able highlight validation problems on controller under create action valid?
method. however, if try valid?
in analogous manner, undefined method
valid?' false:falseclass` how can go validating edit form upon submission, such renders edit form again if 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
if see error looks undefined method 'valid?' 'false:falseclass
that means wherever call method :valid?
, object on calling not object expect, instead false
so have 2 instances in code calling @lesson.valid?
, means 1 or both of assignments of @lesson
returning false.
in docs of create, says: the resulting object returned whether object saved database or not.
in docs of update_attributes, says: if object invalid, saving fail , false returned.
so looks problem update_attributes
, apparently returns false
if update unsuccessful.