On 6/3/07, Ian Harding <harding.ian@gmail.com> wrote:
> On 6/3/07, Alexander Staubo <alex@purefiction.net> wrote:
> > Your patch is awful because it would mean there was no way to enter an
> > empty string in the database. A one-character string containing a
> > single space is not an empty string.
>
> Yeah, it is awful ;^) However the existing system is equally awful
> because there is no way to enter NULL!
But there is. One could, quite convincingly, I think, argue that the
parsing of '' (empty string) into nil/null is data model-specific. One
solution, then, is to add this rule to the model:
class User < ActiveRecord::Base
...
def description=(value)
value = nil if value.blank?
self.write_attribute(:description, value)
end
end
You can easily refactor this into a plugin, which you could then invoke thus:
class User < ActiveRecord::Base
null_when_empty :description
...
end
This is getting very Rails-specific, so I'll stop here. I would be
happy to send you the code (it's probably around 15 lines) for such a
plugin privately if you like.
> Properly implemented, the rails model would allow you to indicate
> nullability and use null if no data is provided.
The preferred approach nowadays is not to clutter the Rails (or in
this case, ActiveRecord) core unduly with all sorts of app-specific
solutions, and instead move code out into plugins. Plugins that, over
time, prove to be universally useful, would be considered for
inclusion into the core. So a plugin is a start.
Alexander.