0

We have two models, Question and Answer which are associated:

class Question < ApplicationRecord
    has_one :answer
end

class Answer < ApplicationRecord
    belongs_to: question
end

Under the default setting, the answers table contains a question_id column which is used for this relation. This column holds the automatic enumeration of the questions (question.id), but it presents us some challenges when coming to migrate some old data sets.

Each question has an additional unique identifier called name, which is a string:

<Question id: 355, name: "ABC123", question_type: ...>

We would like to use this attribute as the key for this association. That is, the answers table should contain a question_name column, which will hold the relevant value. We've managed to set up the custom column name and define foreign keys properly, but it always looks for the question_id value rather than the name. Using the above example, it will look for the row where the foreign key is 355 rather than "ABC123".

Is there any way of setting this thing without changing question's primary key (as explained here)? I could obviously override the default association methods (question.answer, answer.question) but then again I'd really like not to.

Spätzle
  • 709
  • 10
  • 20

1 Answers1

-1

The solution is actually pretty simple (using this post):

class Question < ApplicationRecord
    has_one :answer, foreign_key: "question_name", primary_key: "name"
 end
    
class Answer < ApplicationRecord
   belongs_to :question, foreign_key: "question_name", primary_key: "name"
end

The foreign and primary key values could be specified either as strings or symbols.

max
  • 96,212
  • 14
  • 104
  • 165
Spätzle
  • 709
  • 10
  • 20