[英]How to validate virtual attribute in Rails?
I have this class: 我有这门课:
class Project < ActiveRecord::Base
validates :hourly_rate, :numericality => { :greater_than_or_equal_to => 0 },
:allow_blank => true
def hourly_rate=(number)
self.hourly_rate_in_cents = number.present? ? number.to_d * 100 : nil
end
end
Essentially, any new hourly_rate
that gets entered by the user will get saved to the database as an integer. 实质上,用户输入的任何新的
hourly_rate
都将作为整数保存到数据库中。
This works quite well for numbers. 这对数字很有效。
But any string
that is being entered, is automatically converted into 0.0
and gets saved without any validation message! 但是输入的任何
string
都会自动转换为0.0
并在没有任何验证消息的情况下保存!
Isn't there a way to validate this using any of Rails' validation methods? 有没有办法使用任何Rails的验证方法验证这一点?
Thanks for any help. 谢谢你的帮助。
You can create your own validate method and use that to check for the type of object. 您可以创建自己的验证方法,并使用它来检查对象的类型。
For example (and forgive me if there's an error in this code, since it's just off the top of my head): 例如(并且如果此代码中存在错误,请原谅我,因为它只是在我的头顶):
validate :hourly_rate_is_integer
def hourly_rate_is_integer
errors.add(:hourly_rate, "must be Integer") unless self.hourly_rate.is_a?(Integer)
end
If you have a reader method for this that converts the other way, it will work as you expect. 如果你有一个读者方法,以另一种方式转换,它将按预期工作。 You've only shown the assignment method here.
您只在此处显示了分配方法。
def hourly_rate
self.hourly_rate_in_cents and self.hourly_rate_in_cents.to_f / 100
end
All the validation routines do is call the given method and apply tests to the result. 所有验证例程都是调用给定的方法并将测试应用于结果。
You might want to ensure that presence is specifically tested: 您可能希望确保存在经过专门测试:
validates :hourly_rate, :presence => true, ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.