Reputation: 63738
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
Reputation: 5675
That is two functionalities:
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.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