简体   繁体   English

Rails有一对一的关系

[英]Rails has_one relationship

I'm wondering why when i have 1:1 relationship ( has_one , belongs_to ) I am able to insert duplicate IDs via the console. 我想知道为什么当我有1:1的关系( has_onebelongs_to )时,我能够通过控制台插入重复的ID。

For example, there are two child objects which have the same parent in the foreign key. 例如,有两个子对象在外键中具有相同的父对象。

Is is not by default that the foreign key must be unique, or should I include something like unique: true ? 默认情况下,外键不是唯一的,或者我应该包含类似unique: true

It's not the default, though it's not difficult to implement. 它不是默认值,但实现起来并不困难。 First, create a migration to add a uniqueness constraint in the db: 首先,创建一个迁移以在db中添加唯一性约束:

From the terminal: 从终端:

rails g migration add_uniqueness_to_your_table_column

In the generated file: 在生成的文件中:

add_index :table_name, :column, unique: true

More here if you're interested, though the crux is indexes are used to check uniqueness. 如果你感兴趣的话, 更多的是,虽然关键是索引用于检查唯一性。

Then, ensure you have no current duplicates in the db (it will fail otherwise), before running: 然后,确保在db中没有当前重复项(否则将失败),然后运行:

rails db:migrate

Finally, you can also enforce this at the model level, using: 最后,您还可以在模型级别强制执行此操作,使用:

# your_model.rb
validates :column, uniqueness: true

Hope that helps - let me know if you've any questions or comments on this. 希望有所帮助 - 如果您对此有任何问题或意见,请告诉我。

Foreign keys are not unique by default. 外键默认情况下不是唯一的。 Let's look at a practical example where you have an entity type for users and a user might have a boss via a foreign key. 让我们看一个实际示例,其中您有一个用户实体类型,用户可能通过外键拥有一个boss。 By default there might be multiple users who have the same boss. 默认情况下,可能有多个用户拥有相同的boss。 If you need to make it unique, you will need to specify that constraint. 如果需要使其唯一,则需要指定该约束。 And if you need to make sure everyone has a boss, you will need to specify that too. 如果你需要确保每个人都有老板,你也需要指明一下。

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

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