Search code examples
ruby-on-railsactiverecordabstractionabstract-data-type

Abstracting ActiveRecord Attributes


What is the best way to abstract an ActiveRecord attribute without further normalizing the database?

For example, let's assume a database table named addresses with a column zip_code and a method to determine if the zip code is valid:

class Address < ActiveRecord::Base
  def zip_code_valid?
    ..
  end
end

I would prefer to have:

class Address < ActiveRecord::Base
  ..
end

class ZipCode
  def valid?
    ..
  end
end

and when I execute Address.find(1).zip_code, it returns a ZipCode vs. a string. I would prefer not to normalize the database by creating a table called zip_codes. The example is hypothetical, and I currently do not have a real world example of this; I simply want to know how I could potentially do this.

Thank you.


Solution

  • I'm not sure why you'd want to do this for ZipCode as you discussed, but to answer your question, you should consider using Rails Aggregations.

    Here's the documentation :

    http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html

    If you have specific questions about things you want to accomplish, let me know and I can try to answer those specific questions.