First: I've found this topic but it does not work.
I have a relation between two models
Council(1)<->(n)Department
and I want to insert a council without a relation to a department.
I've got this ecto schema:
schema "councils" do
field :name, :string
field :description, :string
belongs_to :department, Db2.Department
many_to_many :students, Db2.Student, join_through: Db2.StudentCouncil
many_to_many :periods, Db2.Period, join_through: Db2.StudentCouncil
timestamps()
end
with this SQL schema:
CREATE TABLE public.councils
(
id integer NOT NULL DEFAULT nextval('councils_id_seq'::regclass),
name character varying(255),
description character varying(255),
department_id integer,
inserted_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
CONSTRAINT councils_pkey PRIMARY KEY (id),
CONSTRAINT councils_department_id_fkey FOREIGN KEY (department_id)
REFERENCES public.departments (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
The documentation says that cast/4
is deprecated, but phoenix created the changeset with cast/3
& validate_required/3
by itself. I only added the department
so that I have the following changeset:
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:name, :description, :department_id])
|> validate_required([:name])
|> unique_constraint(:name)
|> assoc_constraint(:department)
end
For the form I'am using the the default phoenix.html form elements. When I submit the form phoenix says the following:
[debug] QUERY OK db=1.2ms queue=0.1ms
SELECT u0."id", u0."uid", u0."is_admin", u0."is_staff", u0."password_hash", u0."inserted_at", u0."updated_at" FROM "users" AS u0 WHERE (u0."id" = $1) [1]
[debug] Processing by Db2.CouncilController.create/2
Parameters: %{"_csrf_token" => "KwpdFCZ/bFN9fwkcXSAYLhRCIzgOAAAAXeoEa4+d1MoT7SvzZpgOdg==", "_utf8" => "✓", "council" => %{"department_id" => "", "description" => "", "name" => "test2"}}
Pipelines: [:browser]
[debug] QUERY OK db=1.2ms queue=0.1ms
#Ecto.Changeset<action: :insert, changes: %{description: "", name: "test2"},
errors: [department_id: {"is invalid", [type: :id]}], data: #Db2.Council<>,
valid?: false>
The problem is that you're sending an empty string as the department_id
instead of nil
. Empty strings are not cast to nil
automatically:
iex(1)> MyApp.Post.changeset %MyApp.Post{}, %{"title" => "Hello"}
#Ecto.Changeset<action: nil, changes: %{title: "Hello"}, errors: [],
data: #MyApp.Post<>, valid?: true>
iex(2)> MyApp.Post.changeset %MyApp.Post{}, %{"title" => "Hello", "user_id" => nil}
#Ecto.Changeset<action: nil, changes: %{title: "Hello"}, errors: [],
data: #MyApp.Post<>, valid?: true>
iex(3)> MyApp.Post.changeset %MyApp.Post{}, %{"title" => "Hello", "user_id" => "1"}
#Ecto.Changeset<action: nil, changes: %{title: "Hello", user_id: 1}, errors: [],
data: #MyApp.Post<>, valid?: true>
iex(4)> MyApp.Post.changeset %MyApp.Post{}, %{"title" => "Hello", "user_id" => ""}
#Ecto.Changeset<action: nil, changes: %{title: "Hello"},
errors: [user_id: {"is invalid", [type: :id]}], data: #MyApp.Post<>,
valid?: false>
You can either explicitly set department_id
to nil
before calling changeset
, or use Phoenix's scrub_params
plug, which does the same thing for all empty strings:
# web/controllers/council_controller.ex
plug :scrub_params, "council" when action in [:create]
(Change "council"
to the field name and [:create]
to the list of actions where you're accepting that field.)