Tuesday, August 8, 2006

Encapsulate Relationships in Rails

It would be really nice if I could encapsulate all of the default accessors that are generated when I create a relationship between two ActiveRecord objects.

For instance, when you declare that `has_and_belongs_to_many :people`, your model is peppered with public accessors for the people collection. These methods are generated for your class at runtime.

I want to provide business logic around those people, and therefore I want to prohibit clients from directly accessing the people collection. I want to provide methods such as `register_person`. Of course, I can add that method, but there's nothing stopping someone from coming along and calling `model.people << person`.

Is there? How to restrict direct access to the collection on an ActiveRecord model?
Post a Comment


I'm probably required to say that the views expressed in this blog are my own, and do not necessarily reflect those of my employer. Also, except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the BSD License.