How to deal with boolean value from form submit?

Viewed 1324

we use checkbox to submit a boolean data in a form.

In rails, when submit the form, a string with "1" or "0" will be submitted to the controller.

In phoenix, when submit the form, a string with "true" or "false" will be submitted to the controller.

It's fine if we directly create object in the database. Either of value will be store as boolean correctly.

But if we need to use the boolean value in our logic, what's the best way to do it?

  1. Convert to boolean:
    # Ruby code
    def create
      admin = ActiveModel::Type::Boolean.new.cast(param[:admin])
      if admin
          ....
      end
    end
  1. Directly use as string:
    # Elixir code
    def create(conn, params) do
      case params[:admin] do
        "true" -> do something
        _ -> do others
      end
    end
  1. Other better ways?
1 Answers

String.to_existing_atom/1 is your friend.

Both true and false are atoms, namely a syntactic sugar for :true and :false. That is because in they are atoms.

:true == true
#⇒ true
:false == false
#⇒ true

String.to_existing_atom "true"
#⇒ true
Related