Taking control of form parameters, having 2 replies
One often overlooked problem with creating or updating records with form data is that blank parameters (form fields left blank) are stored in the database as empty strings upon mass assignment.
I see world of difference between nil values and blank strings, and a lot of my code depends on knowing the difference. This being said, one form post can wipe out all of your nil values and replace them with strings unless you're careful.
My favorite way of getting around this has been to reject blank values when I set attributes on an ActiveRecord object.
@user.attributes = params[:user].reject(&:blank?)
In this example, I'm getting rid of any key/value pairs in the user hash that have blank strings as values.
There are numerous ways of taking control of your form posts if you, like me, think that a nil value should mean "nothing's here, because nothing has been assigned", and strings should be reserved for substantive values. I was playing around with this snippet of code for setting default values of nil or empty strings which essentially just acts like Object#blank?.
class Object def or(alt) (respond_to?(:empty?) && empty?) || !self ? alt : self end end ''.or 'Default Value' # => "Default Value" 'Full'.or 'Do nothing' # => "Full" ''.or nil # => nil
I can remember numerous times where the empty string bothered me, especially when those attributes are not part of a validation that requires the presence of non blank? values. Mostly I have just learned to ignore this and always use .blank? in the code when examining these attributes.
However... I can totally see at "some" companies where you have people totally hacking away at the DB and wanting NULL and not getting it as the primary issue. But you know rails... who cares about those people... all data should go thru the app!!!
Yes, I've also become blank? dependent for this reason.
I recently ran into a situation where the methods prescribed above could be a problem. I was attempting to sanitize inputted data, and a particular field came out to be nil, which caused the string methods to fail.
As with everything - moderation and having a well thought out design plan for your app is critical!