I have an simple aggregation in a model class. It maps a single varchar field to
a value object. For some rows in the table for this class this field is null.
When I access an instance of this model object for which the db field is null,
ActiveRecord calls the constructor of the value object with a nil value. While
this makes sense, I would prefer that ActiveRecord instead set this property to
nil in the model object and never call the constructor for the value object.
An example:
CREATE TABLE foo (
id INTEGER NOT NULL,
size VARCHAR(255),
bar VARCHAR(255)
...
)
class Foo < ActiveRecord::Base
composed_of :size, :class_name => "Quantity", :mapping =>
%w(size str)
...
end
class Quantity
def initialize(str)
...
end
end
# yml to initialize the table
first_foo:
id: 1
size: NULL # not sure if this is the correct way to set a null in yaml...
bar: testing
# showing the actual issue
f = Foo.find(1)
When ActiveRecord builds the Foo object it calls Quantity.new(nil). I
don''t want that. I want ActiveRecord to see a null in the size column
of the table and say "Gee, this Foo object must not have a size; I
won''t try to instantiate a Quantity object, and when someone calls the
accessor for it I will return nil." Is this possible?
The most straightforward workaround I see is to disallow null values for sizes
in the database, replace them with empty strings, and extend the functionality
of the Quantity class so that it can represent a nonexistent quantity. That
doesn''t seem very nice.
Kristof