【问题标题】:Missing ecto association between models模型之间缺少 ecto 关联
【发布时间】:2016-12-10 17:55:55
【问题描述】:

我正在关注 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的内容吗?可能缺少has_many :videos, ...
  • 好的,刚刚更新了答案。

标签: erlang elixir phoenix-framework ecto


【解决方案1】:

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

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

如第 6 章(p1_0 PDF 的第 100 页)和this snippet 中所述。

【讨论】:

    【解决方案2】:

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

    错了

    has_many :video, Rumbl.Video
    

    正确

    has_many :videos, Rumbl.Video
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多