Topic: mapping a nil foreign key to a static default

Here is what I'd like:

class ForumPost < ActiveRecord::Base
  belongs_to :forum_thread, :counter_cache => true
  belongs_to :profile, :counter_cache => true, :default => true

  ...

  def author
    profile.person
  end

end


So if ForumPost.profile is nil, instead of causing a blow-out, it should call a method like Profile.default and use the returned object.

I've looked at the bleongs_to code, and I'm not sure (yet) how I could extend it to do what I want, but the above feature is something I could see myself using quite abit.  The alternative is that I check the value myself:

class ForumPost < ActiveRecord::Base
  belongs_to :forum_thread, :counter_cache => true
  belongs_to :profile, :counter_cache => true, :default => true

  ...

  def author
    profile.nil? ? Profile.default.person : profile.person
  end

end


You know... it looks kind of funny to use a method ending in '?' in a terinary operator (x?y:z), but that's beside the point.

I could see having to code the above in several places and models.  I understand that typically it's good practise to ensure no stray nil references exist in the underlying databsae (and possibly overlying code).  The easiest way I suppose is to just not allow nil values in the database -- period.

But there is something to be said for just letting it hang out there.  I mean, I think I'd rather have an author show up as "unknown" vs. getting a database related error (null contraint violation), or rails application error (nil dereference).

Of course the more I think about it, the more difficult this is going to be to implement.  Each model would have to have a default object that is self-sufficient.  So if a profile above has other foreign keys (which in my case it does), it'll be necessary to define the foreign keys to the other default models...

OK.  Maybe it's a bad idea.  Maybe I have to force not null into the databse.  Sorry -- nothing to see here... move along please.

Re: mapping a nil foreign key to a static default

I just think in a higher level language like ruby, it's a pain to sprinkle if (something.nil?) all over the place.  I might just as well be coding in C!