Missing ecto association between models
Asked Answered
R

2

5

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?

Recognize answered 4/8, 2016 at 14:29 Comment(2)
That comment sounds incorrect. Can you please post the contents of web/models/user.ex? There's probably a missing has_many :videos, ....Syllabism
Sure, just updated the answer.Recognize
S
8

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.

Syllabism answered 4/8, 2016 at 14:43 Comment(0)
C
0

In my case the reference was not plural. Was getting the same error.

Wrong

has_many :video, Rumbl.Video

Correct

has_many :videos, Rumbl.Video
Conny answered 8/2, 2019 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.