2017-02-28 36 views
0

不同,当我运行混合ecto.migrate我遇到了一个错误,(ArgumentError) foreign_key :country_id must be distinct from corresponding association name lib/ecto/schema.ex:1499: Ecto.Schema.__belongs_to__/4foreign_key:COUNTRY_ID必须从相应的关联名称

我的目标是我想在我的手机表,这是conutry_id和COUNTRY_CODE添加两个外键。我错过了什么?

这是我的手机模式:

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 

这是我的国家的模式:

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

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

timestamps() 
end 

这是我的迁移脚本:

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 

非常感谢您!

回答

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

这个宏调用的形式是belongs_to :name, QueryAbleModuleName, opts。现在在你的情况下,:name参数和foreign_key选项具有相同的值。通常,foreign_key应该是<name>_id

如果表中有company_id字段,然后调用应该是这样的:

​​

所以,如果你想country_idcountry_code作为协会的名称,请考虑外键country_id_idcountry_code_id,并确保您的数据库模式反映这一点。

或者考虑一下你的情况下更有意义的东西。

相关问题