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:
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
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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With