Don P
Don P

Reputation: 63738

Rails use a non-id column for model associations

How can I specify a column for a Rails model association to use as its foreign_key? This is "id" by default, and I would like to specify another column.


Example:

question.rb

class Question < ActiveRecord::Base
  has_many :answers
end

answer.rb

class Answer < ActiveRecord::Base
  belongs_to :question
end

Both the "questions" and "answers" table do not use the id column. Instead they both use the stack_overflow_id column for their primary_keys (they came from the StackOverflow API).


Here is the code that should be able to run:

my_question = Question.find(stack_overflow_id: 55)
answers = my_question.answers

Upvotes: 1

Views: 2000

Answers (1)

ABMagil
ABMagil

Reputation: 5675

That is two functionalities:

  1. Overriding the foreign key for an association. This is done with the foreign_key parameter on an association: belongs_to :question, foreign_key: "stack_overflow_id". This will allow you to do instance.association and get the correct records back.
  2. Finding a record by parameters, rather than the automatically created ID field. This is accomplished using Model.where(stack_overflow_id: 55) (for more than one record) or by using find_by(stack_overflow_id: 55) (for the first/only record with that ID. Check out the APIs for these commands, because they don't match the API for find.

Upvotes: 2

Related Questions