How to pass NULL through params?

Is there a built-in way for Rails to interpret “” in a params hash as
nil? I don’t want to add empty strings to my database.

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

RSL

I’m trying avoid adding “” to fields on @whatever.save

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?

RSL

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

That works on a single attribute but I’m not quite sure how to do this
to a hash. Something like this?

params.each do {|h, k| @object.k = nil if params[:k].blank?}

Taylor S. wrote:

I’m trying avoid adding “” to fields on @whatever.save

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
end
end

Eric

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

RSL

Thanks for everyone’s help. Here an example of the function I ended up
using:

if params[:person]
  params[:person].delete_if {|key, value| value.blank?}
  @person = Person.new(params[:person])

See how delete_if simplifies things? I knew the Pickaxe was good for
something!

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.

RSL