使用 Elixir 和 Phoenix 框架形成对象

Form objects with Elixir and Phoenix framework

我想知道是否有一种方法可以使用 ElixirPhoenix 框架创建表单对象?我想实现类似于 reform gem 在 Rails 中所做的事情,因为我不喜欢在每种情况下都进行相同的验证 运行,这会导致复杂的代码我的经验。那么我可以创建类似下面的东西并使其以某种方式工作吗?

defmodule RegistrationForm do
  defstruct email: nil, password: nil, age: nil    

  import Ecto.Changeset       

  def changeset(model, params \ :empty) do
    model
    |> cast(params, ["email", "password", "age"], ~w())
    |> validate_length(:email, min: 5, max: 240)       
    |> validate_length(:password, min: 8, max: 240)
    |> validate_inclusion(:age, 0..130)        
  end   

end

这可以在具有虚拟属性的模式上工作:

defmodule RegistrationForm do      
  use Ecto.Schema

  import Ecto.Changeset

  schema "" do
    field :email, :string, virtual: true
    field :password, :string, virtual: true
    field :age, :integer, virtual: true
  end

  def changeset(model, params \ :empty) do
    model
    |> cast(params, ["email", "password", "age"], ~w())
    |> validate_length(:email, min: 5, max: 240)       
    |> validate_length(:password, min: 8, max: 240)
    |> validate_inclusion(:age, 0..130)        
  end   
end

如果您在结构中指定 __changeset__ 函数或值(这是由 schema 宏自动生成的。),这也可以工作 - 但是看起来这可能不是故意的方式来做到这一点。

defmodule RegistrationForm do
  defstruct email: nil, password: nil, age: nil    

  import Ecto.Changeset

  def changeset(model, params \ :empty) do
    model
    |> cast(params, ["email", "password", "age"], ~w())
    |> validate_length(:email, min: 5, max: 240)       
    |> validate_length(:password, min: 8, max: 240)
    |> validate_inclusion(:age, 0..130)        
  end   

  def __changeset__ do
    %{email: :string, password: :string, age: :integer}
  end
end

两者都给出了以下结果:

iex(6)>  RegistrationForm.changeset(%RegistrationForm{}, %{email: "user@example.com", password: "foobarbaz", age: 12}).valid?
true
iex(7)>  RegistrationForm.changeset(%RegistrationForm{}, %{email: "user@example.com", password: "foobarbaz", age: 140}).valid?
false