将NULL插入到ecto当属字段中 [英] Insert null into ecto belongs_to field

查看:82
本文介绍了将NULL插入到ecto当属字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ecto模型

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

但是有时候我想保存到数据库并将用户设置为nil,是否需要在用户字段中添加一些标志?

But sometime I want to save to database and put the user to nil, Need I to add some flag to the user field?

我的控制器中有此代码

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"})

在数据库中插入null的最佳方法是什么?

What is the best way to insert null in the database?

我正在使用postgres,当手动插入数据时,我可以在user_id字段中插入null.

I am using postgres and when insert my data manually I am able to insert null in the user_id field.

推荐答案

没关系,我只是从必填字段中删除了user_id并将其添加到可选字段中

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)

这篇关于将NULL插入到ecto当属字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆