I recently come across this code. User has many Answer. What is the purpose of the :class_name and :foreign_key ?
class Answer < ApplicationRecord
belongs_to :user, :class_name => 'Question", :foreign_key => 'question_id'
end
I recently come across this code. User has many Answer. What is the purpose of the :class_name and :foreign_key ?
class Answer < ApplicationRecord
belongs_to :user, :class_name => 'Question", :foreign_key => 'question_id'
end
The naming here is kind of strange, but the purpose of :class_name
is to allow you to use a class that is different from the one Rails expects. When you have a belongs_to :user
on a model, Rails would expect that to point to a parent class called User
. In your example, Rails skips looking for a User
class and instead looks to the Question
model.
The most common usage of this, though, is when a non-default association name makes more sense than the default. So a more apt example is when you have a User
model and Competition
model wherein each competition has one user as a winner. You could have each Competition
belong to a User
, but that wouldn't be as expressive. Instead you may want to have the relationship be referred to as winner
:
class User < ActiveRecord::Base
has_many :winners, class_name: "Competition", foreign_key: "competition_id"
end
class Competition < ActiveRecord::Base
belongs_to :winner, class_name: "User", foreign_key: "winner_id"
end
This allows you to refer to users as winners
:
competition = Competition.first
competition.winner
This is a lot more expressive than if you were to write competition.user
.