ruby-on-railsdatabase-migrationmodifiers

Add references to a chosen column different from id


Is it possible to add references to a column different from the id column?

Usually when a relationship between two models (Model1 and Model2) is created, the use of model1:references and model2:references for the creation of the Relationship model automatically adds a model1_id and model2_id column (along with an index and a foreign key reference) for use in the model1/model2 association:

rails generate Relationship model1:references model2:references

Say for instance Model1 = Teacher and Model2 = Pupil.
Suppose that Model2's records (pupils' records) are updated every now and then with a rake task: the values of its attributes (for instance name and school_credits) would change, preserving id and ranking (1 to 100).

Associate a teacher with a pupil_id would not have much sense.
Each teacher should be instead associated with his/her pupils' names using as a foreign key reference the attribute pupil.name instead of pupil.id.

Is that possible?
What options can I add to the command rails generate Relationship or what reference am I supposed to add to have this result?


Solution

  • Yes, you can. Check sections on foreign_key and primary_key from the following link. I don't use generator so I cannot comment on which options to pass into generator, but you just need to ensure that the column to be used as foreign key exists in your table and that you assign appropriate foreign_key in the model files.

    But why do you need it? I don't understand what kind of use case you might have that would require you to keep id and ranking identical.