模型之间缺少 ecto 关联

Missing ecto association between models

我正在阅读 Chris McCord 的 "Programming Phoenix" 一书,在第 6 章中,在 UserVideo 之间创建了关系。

当尝试 运行 它与 mix phoenix.server 时,出现以下错误:

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

查看本书的勘误表,另一位用户的评论提到发生这种情况是因为登录用户没有任何与其关联的视频。

以下是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 

如何优雅地处理这种情况?

您忘记在 web/models/user.ex 中的 schema "users" 中添加 has_many :videos, Rumbl.Video:

schema "users" do
  # ...
  has_many :videos, Rumbl.Video
  # ...
end

如第 6 章(p1_0 PDF 第 100 页)和 this snippet.

中所述

在我的例子中,引用不是复数。遇到同样的错误。

错误

has_many :video, Rumbl.Video

正确

has_many :videos, Rumbl.Video