Associations without indexing

75 Views Asked by At

let's say I have a one to one relationship between two models. I create the relationship has_one and belongs_to in respective classes. Before migrating I connect the two tables using t.references :table_name, foreign_key:true. Will rails enforce one to one relationship? I was able to link the same row, multiple times in the other table without any error.

Only, when I rolled back and added index:{unique:true} it started saying that you already have linked that row, thus maintaining the one-to-one relationship. So, the question is what's the use of creating associations, if rails can't enforce it?

I know I am missing something, but I am unable to find it.

1

There are 1 best solutions below

0
max On

You're expecting something very unrealistic.

The role of assocations in Rails is not to enforce the consistency of your data because that's impossible for any application to actually do. Enforcing the consistency of the data is ultimately the responsibility of the database.

(c) Thoughtbot

Assocations are an object oriented abstraction around the relations between your database tables. They make it easier to query related data and load models and their assocations. It's also a very leaky abstraction and the Object–relational impedance mismatch problem is everywhere - however that doesn't mean its not an extemely useful tool when used right.

In the case of belongs_to it can only actually ever point to one record since its joining on a foreign id stored on this models table. That column can only store one value (unless you're doing something very wrong).

has_one gives no guarentee that there is actually one single possible record on the other end. It just joins the other table and puts a limit on the query so that you only get a single record. If you have multiple records on the other table that match you'll get the first in whatever order the records were fetched in.

Enforcing uniqueness is the role of unique constraints in the database together with validations in the model that catch most violations before they cause a database driver error and provide user feedback.