How to pass NULL through params?

You can test for params[:whatever].blank? which is essentially [AFAIK] nil entries in a form.


It already comes through the form as an empty string. Perhaps something like

object.attribute = nil if params[:attribute].blank?

is what you’re looking for. I personally don’t worry about whether it’s saving an empty string or a nil value and instead check for object#nil? or object#blank? [in that order] when testing an attribute’s value.

It just occurred to me that this might not be the most Ruby way. Anyone else?


Taylor Strait wrote:

I'm trying avoid adding "" to fields on

What about doing it at the object level? Something like:

class Foo < ActiveRecord::Base
   def bar=(bar)
     bar = nil if bar.blank?
     self[:bar] = bar


Precisely. And the before_save callback is a great place to put that!


I might not do params[:each] since there are non-field-inputted params in there [like :id, etc] as well as the fact that only text-field inputs return empty strings. Checkboxes return 0 and 1, which might need to be handled as true/false instead of nil. Calling them out by name is probably a better choice.