如何在Phoenix中将实例方法添加到模型中



我有这个型号:

defmodule MyApp.MyModel do
  use MyApp.Web, :model
  import Ecto.Query
  # ....

如何向它添加一个实例方法,该方法也使用MyModel上的其他字段?这不起作用,因为在html页面上,它会抛出一个异常,称为the key :my_method not found

defmodule MyApp.MyModel do
  use MyApp.Web, :model
  import Ecto.Query
  # doesn't work
  def my_method do
    # how can I get access to "this" or "self" from here?
    "test"
  end 

由于Elixir是一种函数式编程语言,所以没有方法,只有函数。你也没有"实例"的概念。有一个自函数,用于识别当前进程的PID,但不应将其与其他编程语言中可能习惯的"this"混淆。

函数总是通过以下方式调用:

module.function(arg1, arg2)

因此,要调用示例中的my_method函数(我已将其重命名为my_func),您需要执行以下操作:

def my_func(my_model) do
  my_model.some_attribute
end

这里需要注意的是,必须将结构作为参数传递给函数。然后你可以用来称呼它

foo = %MyModel{}
MyModel.my_func(foo)

http://elixir-lang.org/getting-started/introduction.html是了解长生不老药工作方式的好方法。

最新更新