简体   繁体   English

has_and_belongs_to_many连接表中不允许使用主键

[英]Primary key is not allowed in a has_and_belongs_to_many join table

I have many-to-many linking table between two entities, datacenters and projects, in legacy code. 我在遗留代码中有两个实体,数据中心和项目之间的多对多链接表。 I discovered, that it's really a one to many relationship. 我发现,这真的是一对多的关系。

As a first step to cleaning up the relationship, I wanted to put a unique index on one of the fields. 作为清理关系的第一步,我想在其中一个字段上添加一个唯一索引。

Now I'm getting the following error: 现在我收到以下错误:

Primary key is not allowed in a has_and_belongs_to_many join table (datacenters_projects). has_and_belongs_to_many连接表(datacenters_projects)中不允许使用主键。

I'm using Rails 2.3.8 running on ruby 1.8.7p174 and mysql Ver 14.12 Distrib 5.0.77. 我正在使用在ruby 1.8.7p174和mysql Ver 14.12 Distrib 5.0.77上运行的Rails 2.3.8。

This is not a primary key, it's just a unique index. 这不是主键,它只是一个独特的索引。 I suppose it's a candidate key, but I haven't decided it is a primary key. 我想这是一个候选键,但我还没有确定它是一个主键。

I don't know why mysql considers this to be a primary key. 我不知道为什么mysql认为这是一个主键。 I don't know why ActiveRecord would object to the linking table in a has_and_belongs_to_many having a primary key. 我不知道为什么ActiveRecord会反对具有主键的has_and_belongs_to_many中的链接表。

But my real question is, "Is there any way I can put a unique index on one of the fields, without ActiveRecord giving me an error?" 但我真正的问题是,“有没有什么方法可以在其中一个字段上放置一个唯一索引,而没有ActiveRecord给我一个错误?”

Is there any way I can tell add_index that this is not a primary key? 有什么办法可以告诉add_index这不是主键吗?

I'm not sure why that would fail. 我不确定为什么会失败。 You should be able to get around it using SQL in your migration though, eg: 您应该能够在迁移中使用SQL来解决它,例如:

ActiveRecord::Base.connection.execute("CREATE UNIQUE INDEX project_id_index ON datacenters_projects (project_id)")

Switch to 切换到

has_many :through => ...

Ref: guides 参考: 指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM