ruby on rails - How to handle optional belongs_to association -


usecase:

consider 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 logged-in user creates foo, associated user record. if not logged-in user creates foo, wont associated user. example , have lot of similar use cases in application.

problem:

the problem view code gets cluttered lot of if conditions , ternary operations like,

<% foo.user ? foo.user.name : "not set"%> 

current solution:

to overcome this, using null object design pattern. user class defines nulluser object (whose name set "not set"). if foo object not have user object, return nulluser object. have overridden user method in foo class nil check.

question:

  1. is there better solution this?
  2. is there gem facilitates null object pattern rails active record models.

this sounds perfect case decorator wraps user object. logic display goes in there; view cares can spit out object's name.

draper works decorators in rails.

and railscast measure.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -