Thursday, April 15, 2010

Nil Model Attributes and Lazy-loading

I was working on a project where there was a method in a model that I defined with references to ActiveRecord model attributes like @attribute_name instead of via the accessors like self.attribute_name.

In one route and in one controller, a method checking @attribute_name would return the desired instance of the object. In another route and another controller, it would return nil, even though that attribute was not nil when accessed by its views.

Paul D. mentioned that I should try using an accessor instead of direct attribute reference, and, sure enough, this issue was caused by trying to access an attribute directly that ActiveRecord would have lazy-loaded when retrieved via accessor.

As Paul said, unless the attributes you are working with are ones that you created instead of ActiveRecord's, it is a better idea to use the accessors in your models.

No comments: