[英]Validating attr_accessor, Rails 4
无论出于何种原因,我无法正确验证我的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
使用此代码,所有属性都会通过验证是否应该进行验证。 例如, postal_code
甚至会传递超过10个字符,而其他字符甚至会在空白时传递。
如果我删除if
语句,它们都没有通过。 我得到了每一个错误。 例如,正确填写表格将显示city
不能为空等...
if
语句需要存在,因为这些属性在创建时将为空,并且仅出现在edit
表单中。
如何获得与attr_accessor
一起使用的attr_accessor
?
如果类没有由数据库表备份,则可以使用ActiveModel获取ActiveRecord功能。 您需要做的就是在您的班级中包含该模型。 然后验证将按照您对ActiveRecord的预期运行,并且您不需要条件。
class Foo
include ActiveModel::Model
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.