Search code examples
ruby-on-railshas-one

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?


Solution

  • 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.