How to setup has_one relationship

Where User has_one App_Setting and configured as follows, I get the error message
schema does not have the field :user_id used by association :user, please set the :references option accordingly. What am I missing?


    has_one :app_setting, MyApp.Accounts.AppSetting


  postgres do
    table "app_settings"
    repo MyApp.Repo

    references do
      reference(:user, on_delete: :delete)

  relationships do
    belongs_to :user, MyApp.Accounts.User 


Full stacktrace:

** (ArgumentError) schema does not have the field :user_id used by association :user, please set the :references option accordingly
    (ecto 3.10.3) lib/ecto/association.ex:696: Ecto.Association.Has.struct/3
    (ecto 3.10.3) lib/ecto/schema.ex:1891: Ecto.Schema.association/5
    (ecto 3.10.3) lib/ecto/schema.ex:2044: Ecto.Schema.__has_one__/4
    myapp/accounts/resources/app_setting.ex:1: (file)
    myapp/lib/myapp/accounts/resources/app_setting.ex:1: (file)
    (stdlib 5.0.2) erl_eval.erl:750: :erl_eval.do_apply/7
    (stdlib 5.0.2) erl_eval.erl:136: :erl_eval.exprs/6
    (elixir 1.15.5) lib/enum.ex:2510: Enum."-reduce/3-lists^foldl/2-0-"/3
    (stdlib 5.0.2) erl_eval.erl:750: :erl_eval.do_apply/7
    (stdlib 5.0.2) erl_eval.erl:136: :erl_eval.exprs/6
    (stdlib 5.0.2) erl_eval.erl:1052: :erl_eval.try_clauses/10
    (stdlib 5.0.2) erl_eval.erl:136: :erl_eval.exprs/6
    (stdlib 5.0.2) erl_eval.erl:282: :erl_eval.expr/6
    (stdlib 5.0.2) erl_eval.erl:283: :erl_eval.expr/6
    (spark 1.1.40) myapp/accounts/resources/app_setting.ex:1: Spark.Dsl.__before_compile__/1

Hmm…something looks very strange here. If you comment out the has_one relationship does your application compile as expected? I’m wondering if some other error is causing this somehow.

There must have been some hiccups somewhere. The error is gone now without me doing anything. Sorry for the false alarm.

1 Like