Rails模型.model.valid?返回假却返回true。

huangapple go评论67阅读模式
英文:

Rails model.valid? return falsely returning true

问题

模型验证失败 with_context

模型

class Course < ApplicationRecord
  with_options on: :basic_info_steps do
    validates :name, presence: true
  end
end

控制器

def create
  @user = current_user
  @course = Course.new(session[:course_attributes])
  @course.assign_attributes(course_params)
  if @course.valid?(context: :basic_info_steps)
    session[:course_attributes].merge!(@course.attributes)
    redirect_to [:new, :courses, :details_info_steps]
  else
    render :new, status: :unprocessable_entity
  end
end

@course = Course.new(session[:course_attributes])
=> #<Course id: nil, name: "", actived: true...

名称为空但

@course.valid?(context: :basic_info_steps)
=> true

@course.save(context: :basic_info_steps)
=> false

英文:

The model validation fail with_context

model

class Course &lt; ApplicationRecord
  with_options on: :basic_info_steps do
    validates :name, presence: true
  end
end

controller

def create
  @user = current_user
  @course = Course.new(session[:course_attributes])
  @course.assign_attributes(course_params)
  if @course.valid?(context: :basic_info_steps)
    session[:course_attributes].merge!(@course.attributes)
    redirect_to [:new, :courses, :details_info_steps]
  else
    render :new, status: :unprocessable_entity
  end
end

>> @course = Course.new(session[:course_attributes])
=> #<Course id: nil, name: "", actived: true......

Name is empty but

>> @course.valid?(context: :basic_info_steps)
=> true

>> @course.save(context: :basic_info_steps)
=> false

答案1

得分: 1

惊讶的是,对于设置 valid?save 方法的上下文,语法是不同的,因此这样可以工作:

class Course &lt; ApplicationRecord
  validates :name, presence: true, on: :basic_info_steps
end

course = Course.new(name: &quot;&quot;)

course.valid?(:basic_info_steps) #=&gt; false
course.save(context: :basic_info_steps) #=&gt; false
#但是:
course.valid?(context: :basic_info_steps) #=&gt; true,很奇怪吧?
英文:

surprisingly the syntax is different for setting the context for the valid? and save methods*, so this works:

class Course &lt; ApplicationRecord
  validates :name, presence: true, on: :basic_info_steps
end


course = Course.new(name: &quot;&quot;)

course.valid?(:basic_info_steps) #=&gt; false
course.save(context: :basic_info_steps) #=&gt; false
#but:
course.valid?(context: :basic_info_steps) #=&gt; true, weird huh?

* see rails guides

huangapple
  • 本文由 发表于 2023年5月28日 05:07:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定