1

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?

Alex Heil
  • 345
  • 2
  • 18
  • Please post what error you're getting – uday Apr 09 '16 at 23:00
  • Are you using attr_acessor method because these fields are not saved to a db table? – margo Apr 09 '16 at 23:05
  • Yes, none of the attributes will be saved to my database. They are passed to an API. – Alex Heil Apr 09 '16 at 23:11
  • I'm not sure of your exact use case, but you can use `valid?` on a non-persisted model and it will run the validations without saving it. If you are certain you want to overwrite model getter methods, you may want to check this post http://stackoverflow.com/questions/21835116/how-can-i-overwrite-a-getter-method-in-an-activerecord-model – Petr Gazarov Apr 10 '16 at 03:22

1 Answers1

0

If the class is not backed up at all by a database table, you can use ActiveModel to get ActiveRecord functionality. 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.

class Foo
  include ActiveModel::Model
end
margo
  • 2,927
  • 1
  • 14
  • 31