How to suppress invalid association warning?

I have two schemas:

defmodule Account do
  schema "account" do
    has_many :transfer, Transfer
  end
end

defmodule Transfer do
  schema "transfer" do
    belongs_to :from_account, Account
    belongs_to :to_account, Account
  end
end

This produces the following warning:
warning: invalid association 'transfer' in schema Account: associated schema Transfer does not have field 'account_id' lib/storage/schema/account.ex:1: Account (module)

Can I resolve this with the foreign_key or references options from the has_many/3? The actual foreign keys in the “transfer” table are “from_account_id” and “to_account_id”; both reference “id” in the “account” table.

Maybe like this…

defmodule Account do
  schema "account" do
    has_many :transfer_from, Transfer, foreign_key: :from_account_id
    has_many :transfer_to, Transfer, foreign_key: :to_account_id
  end
end

defmodule Transfer do
  schema "transfer" do
    belongs_to :from_account, Account, foreign_key: :from_account_id
    belongs_to :to_account, Account, foreign_key: :to_account_id
  end
end

Then, when You want to get all transfers for an account, You can use condition like

where([t], t.from_account_id == ^account.id or t.to_account_id == ^account.id)

2 Likes

Yeah, you’re right. I just realized I never tried preloading Transfers from an Account. It fails as the warning suggests because it can’t find the correct association. I didn’t realize I had this problem.

Thanks!