belongs_to association foreign_key option (Rails Guide personal translation)

Rails convention assumes that for column names on join tables that hold foreign keys that point to the other model, the association name with the suffix_id added to the model name will be used. You can specify the name of the foreign key directly with the: foreign_key option.


-Rails Guide

By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:


--Translation for yourself

Rails convention assumes that the column name that holds the foreign key in this model is the association name with the suffix _id. You can use the: foreign_key option to specify the column name that holds the foreign key.


Foreign_key that Rails customarily assumes

class Book < ApplicationRecord
  belongs_to :author(, foreign_key: author_id)
end

Rails expects a foreign_key with __id in the association name, so the: foreign_key option is needed in the example below.

class Book < ApplicationRecord
  belongs_to :author, class_name: "Patron",
                        foreign_key: "patron_id"
end

Recommended Posts

belongs_to association foreign_key option (Rails Guide personal translation)
belongs_to, has_many Default setting of: foreign_key option for association
[Rails] Model Association (Association)
A brief summary of Rails association options (foreign_key, primary_key)