Elixir中的这个别名是什么意思?

时间:2017-02-20 23:05:14

标签: elixir

https://github.com/wojtekmach/acme_bank/blob/master/apps/bank/lib/bank/model.ex#L10

alias Bank.{
  Account,
  Customer,
  Deposit,
  Ledger,
  Repo,
  Transfer,
  Entry
}

没有它,我得到Ecto.Queryable not implemented for Foo, the given module does not exist。如何将Ecto查询内容添加到模型中?

2 个答案:

答案 0 :(得分:4)

这相当于做

alias Bank.Account
alias Bank.Customer
alias Bank.Deposit
alias Bank.Ledger
alias Bank.Repo
alias Bank.Transfer
alias Bank.Entry

当您有多个以相同前缀开头的模块时,此表单只允许您保存一些按键。

至于你的错误,代码可能正在执行类似

的操作
Repo.all(from a in Account)

由于您评论/删除了此别名,Account不再具有任何意义。

答案 1 :(得分:1)

在Elixir中(以及实际上使用任何其他语言),您应该将代码组织到一个上下文中,该上下文根据其功能对多个模块进行分组。在这种情况下,公共上下文是Bank

如上所述,

alias Bank.{
  Account,
  Customer,
  Deposit,
  Ledger,
  Repo,
  Transfer,
  Entry
}

只是为此的快捷方式:

alias Bank.Account
alias Bank.Customer
alias Bank.Deposit
alias Bank.Ledger
alias Bank.Repo
alias Bank.Transfer
alias Bank.Entry

如果您删除alias,则您的模块将不再意识到这些别名,并且当您调用Repo.all(from a in Account)时,它将尝试在不存在的Account模块上执行此命令(应该是Bank.Account)。

别名为responsible for giving an alternative name to a given module