Reputation: 3992
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?
# Ruby code
def create
admin = ActiveModel::Type::Boolean.new.cast(param[:admin])
if admin
....
end
end
# Elixir code
def create(conn, params) do
case params[:admin] do
"true" -> do something
_ -> do others
end
end
Upvotes: 2
Views: 2320
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 erlang they are atoms.
:true == true
#⇒ true
:false == false
#⇒ true
String.to_existing_atom "true"
#⇒ true
Upvotes: 3