Search code examples
elixirphoenix-frameworkecto

foreign_key :country_id must be distinct from corresponding association name


When i run mix ecto.migrate I encountered an error, (ArgumentError) foreign_key :country_id must be distinct from corresponding association name lib/ecto/schema.ex:1499: Ecto.Schema.__belongs_to__/4

My goal is i want to add two foreign keys in my mobiles table, which is conutry_id and country_code. What I am missing?

This is my mobiles schema:

schema "mobiles" do
field :number, :string

belongs_to :person, Person.Person
belongs_to :country_id, Person.Country, foreign_key: :country_id
belongs_to :country_code, Person.Country, foreign_key: :country_code
has_many :mobile_audits, Person.MobileAudit, on_delete: :delete_all

timestamps()
end

This is my countries schema:

schema "countries" do
field :code, :string
field :name, :string
field :iso_codes, :string

has_many :mobiles, Person.Mobile, on_delete: :delete_all

timestamps()
end

And this is my migration script:

def change do
alter table(:mobiles) do
  add :country_id, references(:countries, type: :binary_id, column: :id)
  add :country_code, references(:countries, type: :string, column: :code)
end
end

Thank you very much!


Solution

  • belongs_to :country_id, Person.Country, foreign_key: :country_id
    

    This macro call is in the form belongs_to :name, QueryAbleModuleName, opts. Now in your case, the :name argument and the foreign_key option has the same value. Generally, the foreign_key should be <name>_id.

    If the table has company_id field, then the call should look like:

    belongs_to :company, MyModule.Company, foreign_key: :company_id
    

    So if you want country_id and country_code as association names, consider making the foreign keys country_id_id and country_code_id and make sure your database schema reflects that.

    Or think about something more meaningful in your context.