Elixir 确保值不为 0 或 nil

Ben*_*ins 1 elixir

在这个函数中,我需要检查“price”变量是 0 还是 nil,然后再通过执行 将其转换为浮点数priceFloat = price / 1,否则会出现算术错误。

  def insert_product_shop(conn, product_id, shop_id, price) do
    IO.inspect(price, label: "price")
    priceFloat = price / 1 
    changeset = Api.ProductShop.changeset(%Api.ProductShop{p_id: product_id, s_id: shop_id, not_in_shop_count: 0, price: priceFloat})
    errors = changeset.errors
    valid = changeset.valid?
    case insert(changeset) do
      {:ok, product_shop} ->
        {:ok, product_shop}
      {:error, changeset} ->
        {:error, :failure}
    end
  end
Run Code Online (Sandbox Code Playgroud)

这样做的惯用方法是什么?

我试过这个,但我仍然得到算术错误:

  def insert_product_shop(conn, product_id, shop_id, price) do
    IO.inspect(price, label: "price")
    case {price} do 
      {price} when price > 0 ->
        priceFloat = price / 1 
        changeset = Api.ProductShop.changeset(%Api.ProductShop{p_id: product_id, s_id: shop_id, not_in_shop_count: 0, price: priceFloat})
        errors = changeset.errors
        valid = changeset.valid?
        case insert(changeset) do
          {:ok, product_shop} ->
            {:ok, product_shop}
          {:error, changeset} ->
            {:error, :failure}
        end
      end
  end
Run Code Online (Sandbox Code Playgroud)

Dog*_*ert 5

你的代码不起作用的原因是因为在 Elixir 中,这nil > 0是真的。你可以这样做:

if price not in [0, nil] do
  ...
else
  ...
end
Run Code Online (Sandbox Code Playgroud)

或者

if is_number(price) and price > 0 do
  ...
else
  ...
end
Run Code Online (Sandbox Code Playgroud)