No ecto communication between models

I follow Chris McCord's book Programming the Phoenix, and in chapter 6 we create a connection between Userand a Video.

When you try to start it using mix phoenix.server, the following error appears:

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 through the errata book, there is a comment from another user who mentions that this is happening because the registered user has no videos associated with them.

The following is the content 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?

+4
source share
1 answer

You forgot to add has_many :videos, Rumbl.Videoinside schema "users"to web/models/user.ex:

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

6 (. 100 p1_0 PDF), .

+5

Source: https://habr.com/ru/post/1650187/


All Articles