0

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?

Asarluhi
  • 1,280
  • 3
  • 22
  • 43
  • If you associate Pupil with a name and pupil's name is changed, how would you determine the association ? – Abhishek Kumar Aug 28 '16 at 10:25
  • Say id 1 rank 1 is Paul with 100 credits, 1d 2 rank 2 is Kevin with 90 credits and id 3 rank 3 is Lea with 80 credits. If Lea earns 30 credits id 1 rank 1 is updated with name Lea and 110 credits. Paul and Kevin change too. If Lea is teacher1's pupil, teacher1 should be associated with Lea and not with id 3. – Asarluhi Aug 28 '16 at 11:06

1 Answers1

1

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.

Harfangk
  • 814
  • 9
  • 18
  • Take for instance Wta rankings (women tennis). They are updated every week. You can use nokogiri to update names and points looking for ranking. It is difficult to keep trace of tennis players ranked out of 100 (that is those who exit from the first 100). – Asarluhi Aug 28 '16 at 12:38