Stephen
Stephen

Reputation: 3992

How to deal with boolean value from form submit?

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?

Upvotes: 2

Views: 2320

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

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

Upvotes: 3

Related Questions