[英]Validating attr_accessor, Rails 4
For whatever reason I cannot get my attr_accessor
attributes to validate correctly. 无论出于何种原因,我无法正确验证我的
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
With this code all attributes pass validation whether they should or not. 使用此代码,所有属性都会通过验证是否应该进行验证。 For example,
postal_code
will pass even with more than 10 characters and others will pass even when blank. 例如,
postal_code
甚至会传递超过10个字符,而其他字符甚至会在空白时传递。
If I remove the if
statement none of them pass. 如果我删除
if
语句,它们都没有通过。 I get every error back. 我得到了每一个错误。 For example, filling out the form correctly will display
city
cannot be blank, etc... 例如,正确填写表格将显示
city
不能为空等...
The if
statement needs to be there because these attributes will be blank on creation and only appear on an edit
form. if
语句需要存在,因为这些属性在创建时将为空,并且仅出现在edit
表单中。
How can I get validations to work with attr_accessor
? 如何获得与
attr_accessor
一起使用的attr_accessor
?
If the class is not backed up at all by a database table, you can use ActiveModel to get ActiveRecord functionality. 如果类没有由数据库表备份,则可以使用ActiveModel获取ActiveRecord功能。 All you need to do is include the model in your class.
您需要做的就是在您的班级中包含该模型。 Then the validations will run as you would expect with ActiveRecord and you don't need the conditionals.
然后验证将按照您对ActiveRecord的预期运行,并且您不需要条件。
class Foo
include ActiveModel::Model
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.