Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

key :user_id not found in. Elixir Preload problems [closed]

I'm trying to add a user_id while building a league struct but it's giving me this error:

** (KeyError) key :user_id not found in: %{__meta__: #Ecto.Schema.Metadata<:built, "leagues">, __struct__: Statcasters.Schema.League, id: nil, inserted_at: nil, name: nil, teams: #Ecto.Association.NotLoaded<association :teams is not loaded>, updated_at: nil, users: #Ecto.Association.NotLoaded<association :users is not loaded>, users_id: nil}
(stdlib) :maps.update(:user_id, {{:., [line: 14], [{:user, [line: 14], nil}, :id]}, [line: 14], []}, %{__meta__: #Ecto.Schema.Metadata<:built, "leagues">, __struct__: Statcasters.Schema.League, id: nil, inserted_at: nil, name: nil, teams: #Ecto.Association.NotLoaded<association :teams is not loaded>, updated_at: nil, users: #Ecto.Association.NotLoaded<association :users is not loaded>, users_id: nil})

Here is my controller:

LEAGUE CONTROLLER

  def new(conn, _params) do
    user = Repo.get!(User, conn.assigns.current_user.id)
    changeset = %League{user_id: user.id}
      |> League.changeset()

    render(conn, "new.html", changeset: changeset)
  end

MODELS

league.ex
  schema "leagues" do
    field :name, :string
    has_many :teams, Statcasters.Teams.Team
    belongs_to :users, Statcasters.Coherence.User

    timestamps()
  end
user.ex
  schema "users" do
    field :name, :string
    field :email, :string
    coherence_schema()
    has_many :leagues, Statcasters.Schema.League

    timestamps()
  end

Do I need to use Repo.preload? I'm not sure what it's telling me to do?

like image 906
Bitwise Avatar asked Dec 12 '25 14:12

Bitwise


2 Answers

If you look at the error closely, it says :user_id not found. Indeed it doesn't exist in the map that's printed, but :users_id does exist. This can only mean that you have a relation named users and not user, which is exactly the problem. belongs_to :users should be belongs_to :user.

like image 143
Dogbert Avatar answered Dec 16 '25 00:12

Dogbert


If you follow this link, https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3 , you will see it is mentioned under Ecto.Schema => Functions => belongs_to/3 => Options

belongs_to(name, queryable, opts \\ [])

:foreign_key - Sets the foreign key field name, defaults to the name of the association suffixed by _id. For example, belongs_to :company will define foreign key of :company_id

In your case, belongs_to :user will define foreign key of :user_id

like image 27
Sandar Avatar answered Dec 16 '25 00:12

Sandar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!