cjm2671
cjm2671

Reputation: 19476

How to validate non-db attributes on an ActiveRecord model?

I have the following class:

class Instance < ActiveRecord::Base
  attr_accessor :resolution
  validates_format_of :resolution, with: /\A\d+x{1}\d+\d/

  def resolution=(res)
    validate!
    (set the resolution etc)
  end

  def resolution
    (get the resolution and return)
  end
end

The resolution attribute is not stored in the database, but is a transient property of the instance.

When it calls validate!, validation fails no matter what what rule is included. Without it, validation doesn't work at all.

How can I validate properly?

Upvotes: 2

Views: 930

Answers (2)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can use =~ operator instead to match a string with regex, using this you can add a condition in setter methods

def resolution=(res)
  if res =~ /\A\d+x{1}\d+\d/
    # do something
  else
    # errors.add(...)
  end
end

but, as you have already used attr_accessor, you don't have to define getter and setter explicitly, the role of attr_accessor is to define getter and setter methods only, you can do this instead

class Instance < ActiveRecord::Base
  attr_accessor :resolution
  validates_format_of :resolution, with: /\A\d+x{1}\d+\d/
end

The above solution will work perfectly!

Hope this helps!

Upvotes: 3

Yury Lebedev
Yury Lebedev

Reputation: 4015

The validate! method should be called after setting the variable. In the given example you call validate! when the value is still nil.

Upvotes: 1

Related Questions