Home > Software design >  Using find_or_create_by with nil and empty string values
Using find_or_create_by with nil and empty string values

Time:01-25

I have a table that I do a find_or_create_by when creating new records. The problem is users can manually edit these records and when they save them some nil fields become empty strings, so when I do a find_or_create_by the identical record is created with nil values where the database record has empty string values.

Is there any simple way to tell find_or_create_by to treat nil and "" the same or a simple way to not save empty string values to the database?

CodePudding user response:

You can call presence on the value being saved - this will give you the value if the value is present, and nil if the value is nil or an empty string:

Thing.find_or_create_by(
  {
    field_one: params[:field_one].presence,
    field_two: params[:field_two].presence,
  }
)

you can demonstrate in the rails console:

> ''.presence
 => nil
> nil.presence
 => nil
> 'abc'.presence
 => "abc"
> 123.presence
 => 123

CodePudding user response:

So ultimately I think the right answer is to use a model callback, so something like this:

  before_save :convert_empty_strings_to_nil

  def convert_empty_strings_to_nil
    attributes.each do |column, value|
      self[column] = nil if value.is_a?(String) && value.empty?
    end
  end
  • Related