ActiveRecord has_one default value

My apologies if this is a dumb question, but I’ve searched around and
haven’t been able to come up with a solution.

Is there a way when specifying a has_one association to specify a
default value for an object if data is missing in the child table. For
instance:

class Student
has_one :university
end

if no university is associated to the student in the database, I would
like to automatically return an instance of NoUniverisity class instead
of it being set to nil. Similar to the NullObject refactoring described
in Fowler’s book.

Any ideas?

Thanks!
Jay

Jay Turpin wrote:

class Student
has_one :university
end

if no university is associated to the student in the database, I would
like to automatically return an instance of NoUniverisity class instead
of it being set to nil. Similar to the NullObject refactoring described
in Fowler’s book.

Warning - untested code:

class Student < ActiveRecord::Base
has_one :university

def university_or_default
old_university || NoUniversity.new
end

alias_method :old_university, :university
alias_method :university, :university_or_default

end

hth

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs