How to save values from CSV into columns defined as boolean?

Currently I have a field inside of my schema defined as:

field :is_residential, :boolean, default: false

In my CSV in the related field I have a true string which then I have to transform into an atom in my code using something clunky like this:

String.to_existing_atom(row[:is_residential])

before I save the row. Is there a better way of doing this ?

You could do something like:

row[:is_residential] == "true"

That will give you a boolean true when you have the string “true”, and false otherwise.

I like making a to_boolean function:

def to_boolean("false"), do: false
def to_boolean("true"), do: true

# this way you can also match on values that might be invalid and do something with them
def to_boolean(_), do: nil
2 Likes