TomKo1
TomKo1

Reputation: 224

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.

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?

Upvotes: 1

Views: 489

Answers (2)

SRack
SRack

Reputation: 12203

It's not the default, though it's not difficult to implement. First, create a migration to add a uniqueness constraint in the 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:

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.

Upvotes: 3

Lajos Arpad
Lajos Arpad

Reputation: 76424

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. By default there might be multiple users who have the same 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.

Upvotes: 0

Related Questions