使用Elixir和Phoenix框架形成对象

NoD*_*ame 10 elixir ecto phoenix-framework

我不知道是否有是创建表单对象的方式ElixirPhoenix框架?我想实现类似于reformgem所做的事情,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
Run Code Online (Sandbox Code Playgroud)

Gaz*_*ler 15

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

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
Run Code Online (Sandbox Code Playgroud)

如果__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
Run Code Online (Sandbox Code Playgroud)

两者都给出以下结果:

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
Run Code Online (Sandbox Code Playgroud)

  • 小提示:那些模型可以只是"使用Ecto.Schema".您可能不需要回调等模型职责,只需要结构.除此之外,完美的答案! (4认同)