foreign_key:country_id必须与对应的关联名称不同

时间:2017-02-28 03:30:48

标签: elixir phoenix-framework ecto

当我运行mix ecto.migrate时遇到错误(ArgumentError) foreign_key :country_id must be distinct from corresponding association name lib/ecto/schema.ex:1499: Ecto.Schema.__belongs_to__/4

我的目标是想在我的移动电话表中添​​加两个外键,即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 个答案:

答案 0 :(得分: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字段,则调用应如下所示:

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

因此,如果您希望country_idcountry_code作为关联名称,请考虑创建外键country_id_idcountry_code_id,并确保您的数据库架构反映出来。

或者考虑在你的背景下更有意义的事情。

相关问题