Ecto: Field is already in the schema

Created on 19 Nov 2016  路  5Comments  路  Source: elixir-ecto/ecto

Hi
I created following schema:

schema "countries" do

    belongs_to :code, CountryCode, foreign_key: :alpha2
    belongs_to :language, LanguageCode, foreign_key: :code
    field :text, :string

    timestamps
end

So when I want to migrate it, it tells me

(ArgumentError) field/association :code is already set on schema

In my opinion, it shouldn't be an error, because the code belongs to LanguageCode schema.

Thanks

Most helpful comment

Another way to look at it is "the foreign key points to the referenced column, this means the referenced columns must exist before the foreign key is created".

All 5 comments

I believe you are misunderstanding Ecto belongs_to. For a belongs_to, the :foreign_key is the one defined in the current schema. We are using the database terminology here. Maybe you wanted to write it as:

belongs_to :code, CountryCode, references: :alpha2
belongs_to :language, LanguageCode, references: :code

?

Ah ok. What is the difference between foreign_key and references. I read the doc and could not configure it out. May can you please explain me?

Thanks jose for helping.

Please use the elixir forum or StackOverflow for questions/help, where a wider community will be able to help you. We reserve the issues tracker for issues only. Thank you.

The references field is one that exists in the referenced table. The foreign_key is the field containing the reference in the referencing table.

@kostonstyle the foreign_key is the field that points to the referenced one. for example, for posts has many comments, the comment has a foreign key of comment_id that references the posts primary key called id.

Another way to look at it is "the foreign key points to the referenced column, this means the referenced columns must exist before the foreign key is created".

Was this page helpful?
0 / 5 - 0 ratings