Error with Ecto "does not have association"

I bought the book Phoenix Web Development from Brandon Richey which proposes to program a simple voting application where a poll has many options and an option belongs to a poll. Polls and options are defined as follows:

defmodule Vocial.Votes.Poll do
  use Ecto.Schema
  import Ecto.Changeset
  alias Vocial.Votes.Poll
  alias Vocial.Votes.Option

  schema "polls" do
    field :title, :string
    has_many :options, Option

    timestamps()
  end

  def changeset(%Poll{}=poll, attrs) do
    poll
    |> cast(attrs, [:title])
    |> validate_required([:title])
  end
end
defmodule Vocial.Votes.Option do
  use Ecto.Schema
  import Ecto.Changeset
  alias Vocial.Votes.Option
  alias Vocial.Votes.Poll

  schema "options" do
    field :title, :string
    field :votes, :integer, default: 0

    belongs_to :poll, Poll

    timestamps()
  end

  def changeset(%Option{}=option, attrs) do
    option
    |> cast(attrs, [:title, :votes, :poll_id])
    |> validate_required([:title, :votes, :poll_id])
  end
end

I obtain the error message:

** (ArgumentError) schema Vocial.Votes.Poll does not have association :options
    (elixir) lib/enum.ex:1940: Enum."-reduce/3-lists^foldl/2-0-"/3

whenever I launch the command poll = Repo.get!(Poll, 1) |> Repo.preload(:options) in iex.

Any idea of what could be wrong?

Environment:

  • Elixir version: Elixir 1.8.1
  • Database: PostgreSQL 11.2
  • Ecto version (mix deps): 3.1.1
  • Database adapter and version (mix deps): postgrex 0.14.2

Hey @Okidoki did you try restarting your IEX session? Everything you’ve got looks correct. If I copy and paste the code you have I get:

iex(3)> Vocial.Votes.Poll.__schema__(:associations)
[:options]

Indeed, everything works perfectly after restarting the IEX session. Thank you so much Ben!

1 Like