无论出于什么原因,我都无法正确地验证我的attr_accessor属性。
attr_accessor :line1, :city, :postal_code, :state, :personal_id_number, :ssn_last_4, :bank_account_number, :bank_routing_number
validates :line1, presence: true, if: :line1
validates :city, presence: true, if: :city
validates :postal_code, presence: true, length: { maximum: 10 }, if: :postal_code
validates :state, presence: true, length: { maximum: 2 }, if: :state
validates :personal_id_number, presence: true, numericality: { only_integer: true }, if: :personal_id_number
validates :ssn_last_4, presence: true, length: { is: 4 }, numericality: { only_integer: true }, if: :ssn_last_4
validates :bank_account_number, numericality: { only_integer: true }, if: :bank_account_number
validates :bank_routing_number, numericality: { only_integer: true }, if: :bank_routing_number有了这段代码,所有属性都会通过验证,无论它们是否应该通过验证。例如,即使超过10个字符,postal_code也会通过,而其他字符即使为空也会通过。
如果我删除if语句,它们都不会通过。我把所有的错误都找回来了。例如,正确填写表单将显示city不能为空,等等。
if语句需要存在,因为这些属性在创建时将为空,并且只出现在edit表单上。
如何让验证与attr_accessor配合使用
发布于 2016-04-10 18:39:57
如果类根本不是由数据库表备份的,那么可以使用ActiveModel来获得ActiveRecord功能。您所需要做的就是将模型包含在您的类中。然后,验证将按照您对ActiveRecord的期望运行,并且不需要条件条件。
class Foo
include ActiveModel::Model
endhttps://stackoverflow.com/questions/36523608
复制相似问题