0

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:

  1. Is there a better solution to this?
  2. Is there a gem which facilitates the null object pattern for rails active record models.
manoj
  • 1,655
  • 15
  • 19

2 Answers2

1

This sounds like the perfect case for a decorator that wraps your user object. All the logic about what to display goes in there; all your view cares about is that it can spit out the object's name.

Draper works well for decorators in Rails.

And a Railscast for good measure.

sevenseacat
  • 24,699
  • 6
  • 63
  • 88
0

One potential solution would be to set a default value and associate it with a guest user. That way it would be overridden when a user was present, but would mean there would always be a value when you call .user.name

muttonlamb
  • 6,341
  • 3
  • 26
  • 35