USECASE:
Consider the following example.
Class Foo < ActiveRecord::Base
belongs_to :user
attr_accessible :title
end
Class User < ActiveRecord::Base
has_many :foo
attr_accessible :name
end
If a logged-in user creates Foo, it will be associated to its user record. If a not logged-in user creates Foo, it wont be associated to any user. This is just an example and I have a lot of similar use cases in my application.
PROBLEM:
The problem is my view code gets cluttered with a lot of if conditions and ternary operations like,
<% foo.user ? foo.user.name : "not set"%>
CURRENT SOLUTION:
To overcome this, I am using the null object design pattern. The User class defines a NullUser object (whose name will be set to "not set"). If a foo object does not have user object, it will return a NullUser object. I have overridden the user method in Foo class which does the nil check.
QUESTION:
- Is there a better solution to this?
- Is there a gem which facilitates the null object pattern for rails active record models.