I'm working on some Phoenix framework and i have encountered a weird problem (as usual). Whenever I try to create some Users, i get User with all fields set to nil. I'm using Mongo.Ecto/
def post_login(conn, %{"login" => login, "password" => password}) do
# IO.inspect Plug.Conn.read_body(conn)
a = User.changeset(%User{}, %{"login" => "login", "password" => "password"})
IO.inspect a
Repo.insert( a )
redirect conn, to: "/default"
end
And the model:
defmodule HelloWorld.User do
use HelloWorld.Web, :model
@primary_key {:id, :binary_id, autogenerate: true}
schema "users" do
field :login, :string
field :password, :string
end
@required_fields ~w()
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
And the screen from console:
As you can see in the picture, both login and password fields are nils which makes me feel I've done something incredibly stupid.
The fields need to exist in the options to the cast/4 function:
@required_fields ~w()
@optional_fields ~w(login password)
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
Anything that is in required_fields
but not in the params
will add an error to that field on the changeset. If you want the fields to be required just move them to the required_fields
list.