如何在 Ecto 迁移中为小数列设置默认值?
How do you set a default value for a decimal column in an Ecto migration?
我尝试执行以下操作:
add :balance, :decimal, default: 0.0
add :balance, :decimal, default: "0.0"
add :balance, :decimal, default: Decimal.new("0.0")
前两个根本不起作用,因为如果我没有明确传递值,新创建的记录仍然 return nil
。
第三个return出现这个错误:
** (ArgumentError) unknown default #Decimal<0.0>
for type :decimal
. :default may be a string, number, boolean, list of
strings, list of integers, map (when type is Map), or a fragment(...)
我现在能想到的唯一解决方法是使用 put_change/3:
def changeset(account, attrs) do
account
|> put_change(:balance, Decimal.new("0.0"))
end
但是,我更喜欢在迁移本身上执行此操作。我该怎么做?
我在 Elixir Slack 上问过同样的问题,有人告诉我第一个应该可以。
我再次检查,第一个确实有效。只是 Repo.insert()
returns 列为 nil
,但如果我再次检索记录,它显示为 #Decimal<0E-10>
,这意味着默认值有效。
我尝试执行以下操作:
add :balance, :decimal, default: 0.0
add :balance, :decimal, default: "0.0"
add :balance, :decimal, default: Decimal.new("0.0")
前两个根本不起作用,因为如果我没有明确传递值,新创建的记录仍然 return nil
。
第三个return出现这个错误:
** (ArgumentError) unknown default
#Decimal<0.0>
for type:decimal
. :default may be a string, number, boolean, list of strings, list of integers, map (when type is Map), or a fragment(...)
我现在能想到的唯一解决方法是使用 put_change/3:
def changeset(account, attrs) do
account
|> put_change(:balance, Decimal.new("0.0"))
end
但是,我更喜欢在迁移本身上执行此操作。我该怎么做?
我在 Elixir Slack 上问过同样的问题,有人告诉我第一个应该可以。
我再次检查,第一个确实有效。只是 Repo.insert()
returns 列为 nil
,但如果我再次检索记录,它显示为 #Decimal<0E-10>
,这意味着默认值有效。