cjm2671
cjm2671

Reputation: 19466

Rails ActiveRecord non db attributes?

I've got an ActiveRecord model, Instance, which is based in the database, but has some non-database attributes.

One example is 'resolution'.

I need to be able to set/get the resolution, but this attribute needs custom non-db setters/getters. Where do I put these & how do I structure my model?

I also need to be able to validate resolutions as they are set via regex. Can I use validates_format_of or do I need to code a custom Validator?

Upvotes: 3

Views: 1619

Answers (1)

Yury Lebedev
Yury Lebedev

Reputation: 4015

If you need standard reader/writer methods, you can use attr_accessor:

class Instance
  attr_accessor :resolution
end

You can also write the reader and writer method by yourself:

class Instance
  def resolution
    @resolution
  end

  def resolution=(value)
    @resolution = value
    validate! # this will raise RecordInvalid if the validation fails
  end
end

Upvotes: 4

Related Questions