【问题标题】:Insert null into ecto belongs_to field将 null 插入 ecto belongs_to 字段
【发布时间】:2015-11-18 01:41:35
【问题描述】:

我有一个外模

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

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

我的控制器中有这段代码

changeset = Profile.changeset(%Profile{user_id: nil}, profile_params)

但是当我尝试保存时,我得到了这个错误

:erlang.byte_size({:user_id, "can't be blank"})

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

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

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

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

    @required_fields ~w(name last_name)
    @optional_fields ~w(second_surname user_id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2014-08-15
      • 2018-10-14
      • 2011-04-01
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多