我以这种方式在我的项目中使用Amnesia:
use Amnesia
defdatabase Database do
deftable Account, [{:id, autoincrement}, :email, :account_number, :password, :amount],
type: :set, index: [:email, :account_number] do
@type t :: %Account{
id: non_neg_integer,
email: String.t,
account_number: String.t,
amount: integer
}
def money_transfer(from_account_number, to_account_number, amount) do
from_account = Account.where(account_number == from_account_number)
...
end
end
end
在我的函数money_transfer/3
中,我需要在Account
表上获取帐户,但函数where
不起作用:
warning: variable "account_number" does not exist and is being expanded to "account_number()", please use parentheses to remove the ambiguity or change the variable name
lib/Database.ex:22
== Compilation error in file lib/Database.ex ==
** (CompileError) lib/Database.ex:22: undefined function account_number/0
(stdlib) lists.erl:1338: :lists.foreach/2
lib/Database.ex:4: (module)
➜
如何解决?我不知道为什么会出现此错误,因为account_number
是deftable
上声明的列。我跟着Amnesia readme。
答案 0 :(得分:1)
Reading the tests of Amnesia,我找到了解决方案:
defdatabase Database do
deftable Account, [{:id, autoincrement}, :email, :account_number, :password, :amount],
type: :set, index: [:email, :account_number] do
...
def get_account_by_account_number(by_account_number) do
accounts_by_account_number = where(account_number == by_account_number)
case Amnesia.Selection.values(accounts_by_account_number) do
[account] -> {:ok, account}
[] -> {:error, "not found account"}
end
end
当你在detable
内创建一个函数时,你不应该使用它
表的名称。您应该只使用where
函数。
我不太清楚为什么会这样做。