Insert null into ecto belongs_to field

2019-08-14 05:26发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-14 05:54

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)
查看更多
登录 后发表回答