This are my notes in the fields of computer science and technology. Everything is written with ABSOLUTE NO WARRANTY of fitness for any purpose. Of course, feel free to comment anything.

Friday, August 22, 2008

Hide attributes in Rails / ActiveRecord

Let's assume you have a table "entities" that was created by this Rails migration code:
create_table :entities do |t|
  t.string :type
t.string :title
t.string :first_name
t.string :last_name
t.binary :logo
end
Person and Organisation will be subclasses of Entity (which of course is a subclass of ActiveRecord::Base), using single table inheritance.

If people have no logo and organisations have no title, first name and last name, maybe we would like to hide this columns from their respective classes. Of course, you may say that in this case you shouldn't use STI. But if you really want to... ActiveRecord does not provide hiding functionality. All Person and Organisation instances will see all attributes of Entity. This behaviour can be changed as follows.

When a new object is created (e.g. Person.new), this is a real instance of Person. The list of attributes comes in this case from the public class method columns of ActiveRecord::Base. When records are fetched using a finder method, however, (e.g. Person.first), ActiveRecord goes another way, and calls the private class method instantiate of ActiveRecord::Base, which takes an hash of attributes/values as argument, which conversely derive from the results of the sql query. So to hide attributes you have to hide them both in columns and in instantiate and the trick is done.

No comments:

About Me

My photo
Hamburg, Hamburg, Germany
Former molecular biologist and web developer (Rails) and currently research scientist in bioinformatics.