Getting a warning on using references

Here are my schema and migrations respectively:

defmodule SecureChatBackend.ElipticCurveSignedPrekeys do
  use Ecto.Schema
  import Ecto.Changeset

  schema "elliptic_curve_signed_pre_keys" do
    field :key, :string

    belongs_to :device, SecureChatBackend.Devices
    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(eliptic_curve_signed_prekey, attrs) do
    eliptic_curve_signed_prekey
    |> cast(attrs, [:key])
    |> validate_required([:key])
  end
end

Migrations

defmodule SecureChatBackend.Repo.Migrations.CreateEllipticCurveSignedPreKeys do
  use Ecto.Migration

  def change do
    create table(:elliptic_curve_signed_pre_keys) do
      add :key, :string

      add :device_id, references(:device)

      timestamps(type: :utc_datetime)
    end
  end
end

defmodule SecureChatBackend.Devices do
  use Ecto.Schema
  import Ecto.Changeset

  schema "device" do
    field :apn, :string
    field :device_id, :integer
    field :gcm, :string
    field :token, :string
    field :token_salt, :string
    field :uuid, :string

    has_many :ec_signed_pre_keys, SecureChatBackend.ElipticCurveSignedPrekeys
    belongs_to :user, SecureChatBackend.User

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(devices, attrs) do
    devices
    |> cast(attrs, [:device_id, :token, :token_salt, :gcm, :apn, :uuid])
    |> validate_required([:device_id, :token, :token_salt, :gcm, :apn, :uuid])
  end
end

Migration

defmodule SecureChatBackend.Repo.Migrations.CreateDevice do
  use Ecto.Migration

  def change do
    create table(:device) do
      add :device_id, :integer
      add :token, :string
      add :token_salt, :string
      add :gcm, :string
      add :apn, :string
      add :uuid, :string

      add :user_id, references(:device)

      timestamps(type: :utc_datetime)
    end
  end
end

And I am getting this warning. Is this only because of the way the compiler is compiling files or is my code incorrect.

warning: invalid association `ec_signed_pre_keys` in schema SecureChatBackend.Devices: associated schema SecureChatBackend.ElipticCurveSignedPrekeys does not have field `devices_id`
  lib/secure_chat_backend/devices.ex:1: SecureChatBackend.Devices (module)

Hello and welcome to this peaceful island of functional programming! :wave:

The pluralization in the name of the SecureChatBackend.Devices schema is what’s causing the confusion.

    has_many :ec_signed_pre_keys, SecureChatBackend.ElipticCurveSignedPrekeys

expects the child association ElipticCurveSignedPrekeys to have a devices_id foreign key, because you’re defining it in a module named Devices. You could use the foreign_key option in has_many (Ecto.Schema — Ecto v3.10.3) to explicitly set the foreign key you want.

If I were you however, I would just use a singular name for the schema module.

3 Likes