英文:
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 < 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 < ApplicationRecord
validates :name, presence: true, on: :basic_info_steps
end
course = Course.new(name: "")
course.valid?(:basic_info_steps) #=> false
course.save(context: :basic_info_steps) #=> false
#但是:
course.valid?(context: :basic_info_steps) #=> true,很奇怪吧?
- 参见 Rails 指南
英文:
surprisingly the syntax is different for setting the context for the valid?
and save
methods*, so this works:
class Course < ApplicationRecord
validates :name, presence: true, on: :basic_info_steps
end
course = Course.new(name: "")
course.valid?(:basic_info_steps) #=> false
course.save(context: :basic_info_steps) #=> false
#but:
course.valid?(context: :basic_info_steps) #=> true, weird huh?
* see rails guides
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论