问题
I have an ecto model
defmodule App.Profile do
use App.Web, :model
alias App.Repo
schema "profiles" do
belongs_to :user, App.User
field :name, :string
field :last_name, :string
field :second_surname, :string
timestamps
end
But sometime I want to save to database and put the user to nil, Need I to add some flag to the user field?
I have this code in my controller
changeset = Profile.changeset(%Profile{user_id: nil}, profile_params)
But when try to save I got this error
:erlang.byte_size({:user_id, "can't be blank"})
What is the best way to insert null in the database?
I am using postgres and when insert my data manually I am able to insert null in the user_id field.
回答1:
Never mind, I just removed user_id from required fields and added to optional fields
@required_fields ~w(name last_name)
@optional_fields ~w(second_surname user_id)
来源:https://stackoverflow.com/questions/33770369/insert-null-into-ecto-belongs-to-field