Insert null into ecto belongs_to field

末鹿安然 提交于 2019-12-11 09:45:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!