I'm following the "Programming Phoenix" book by Chris McCord and in Chapter 6, a relationship is created between a User
and a Video
.
When trying to run it with mix phoenix.server
, the following error shows up:
Request: GET /manage/videos
** (exit) an exception was raised:
** (ArgumentError) schema Rumbl.User does not have association :videos
(ecto) lib/ecto/association.ex:121: Ecto.Association.association_from_schema!/2
Going over the book's errata, there's a comment from another user mentioning that this happens because the logged in user does not have any videos associated with them.
Below is the content of user.ex
defmodule Rumbl.User do
use Rumbl.Web, :model
schema "users" do
field :name, :string
field :username, :string
field :password, :string, virtual: true
field :password_hash, :string
timestamps
end
def changeset(user, params \\ :empty) do
user
|> cast(params, ~w(name username), [])
|> validate_length(:username, min: 1, max: 20)
end
def registration_changeset(user, params) do
user
|> changeset(params)
|> cast(params, ~w(password), [])
|> validate_length(:password, min: 6, max: 100)
|> put_pass_hash()
end
def put_pass_hash(changeset) do
case changeset do
%Ecto.Changeset{valid?: true, changes: %{password: pass}} ->
put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(pass))
_-> changeset
end
end
end
How can I gracefully handle this case?
You forgot to add has_many :videos, Rumbl.Video
inside schema "users"
in web/models/user.ex
:
schema "users" do
# ...
has_many :videos, Rumbl.Video
# ...
end
as mentioned in Chapter 6 (page 100 of the p1_0 PDF) and in this snippet.
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