【发布时间】:2020-08-21 18:21:39
【问题描述】:
相关/固定:Ruby on Rails: Validations on Form Object are not working
我有以下验证..
validates :age, numericality: { greater_than_or_equal_to: 0,
only_integer: true,
:allow_blank => true
}
不是必须的,如果输入需要是一个数字。我注意到,如果有人输入单词而不是数字,则在提交并通过验证后,字段值会变为 0。我希望它为空白或输入的值。
更新:
仍然没有解决方案,但这里有更多信息。
rspec 测试 it "returns error when age is not a number" do
params[:age] = "string"
profile = Registration::Profile.new(user, params)
expect(profile.valid?).to eql false
expect(profile.errors[:age]).to include("is not a number")
end
Rspec 测试失败:
Registration::Profile Validations when not a number returns error when age is not a number
Failure/Error: expect(profile.errors[:age]).to include("is not a number")
expected [] to include "is not a number"
2.6.5 :011 > p=Registration::Profile.new(User.first,{age:"string"})
2.6.5 :013 > p.profile.attributes_before_type_cast["age"]
=> "string"
2.6.5 :014 > p.age
=> 0
2.6.5 :015 > p.errors[:age]
=> []
2.6.5 :016 > p.valid?
=> true
#Form 对象注册:配置文件:
module Registration
class Profile
include ActiveModel::Model
validates :age, numericality: { greater_than_or_equal_to: 0,
only_integer: true,
:allow_blank => true
}
attr_reader :user
delegate :age , :age=, to: :profile
def validate!
raise ArgumentError, "user cant be nil" if @user.blank?
end
def persisted?
false
end
def user
@user ||= User.new
end
def teacher
@teacher ||= user.build_teacher
end
def profile
@profile ||= teacher.build_profile
end
def submit(params)
profile.attributes = params.slice(:age)
if valid?
profile.save!
true
else
false
end
end
def self.model_name
ActiveModel::Name.new(self, nil, "User")
end
def initialize(user=nil, attributes={})
validate!
@user = user
end
end
end
#轮廓模型:
class Profile < ApplicationRecord
belongs_to :profileable, polymorphic: true
strip_commas_fields = %i[age]
strip_commas_fields.each do |field|
define_method("#{field}=".intern) do |value|
value = value.gsub(/[\,]/, "") if value.is_a?(String) # remove ,
self[field.intern] = value
end
end
end
有趣的是,如果将验证移至配置文件模型并检查 p.profile.errors,我会看到预期的结果,但看不到我的表单对象。我需要在我的表单对象上保留我的验证。
【问题讨论】:
-
您可能在某处对值调用
to_i并使用此结果而不是请求中传递的原始值params。 -
没有验证不尝试转换值吗?
-
验证完全不会改变分配的值。我的意思是您可能会在某个地方自己调用
to_i(例如,在实际设置模型属性模型之前或在回调中)。 -
但在我的情况下,价值正在改变。这就是整个问题,很奇怪
-
显示注册/profile.rb
标签: ruby-on-rails ruby ruby-on-rails-6