For whatever reason I cannot get my attr_accessor
attributes to validate correctly.
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.
If I remove the if
statement none of them pass. I get every error back. For example, filling out the form correctly will display city
cannot be blank, etc...
The if
statement needs to be there because these attributes will be blank on creation and only appear on an edit
form.
How can I get validations to work with attr_accessor
?