Derive foreign key from model name in has_many
associations
#42215
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently Active Record derives the foreign key name for
has_many
associations based on the Active Record Base `name. Sometimes when using additional conventions for class names, such as with class name suffixes and prefixes, it makes sense to be able to further customize the foreign key logic to account for a different pattern.Similar to what was done in the case of table names, as Active Record Base extends Active Model Naming, we have already a
model_name
at the class-level that behaves similarly toname
while at the same time giving more flexibility by allowing specifying a custom name and namespacing.This commit changes the foreign key computation in Reflections to infer its value based on the Active Record's
model_name
object instead of its classname
. This allows customization of the foreign key pattern since a distinct instance ofActiveModel::Name
can be used instead.For example, to use
post_id
as foreign key for aPostRecord
class in ahas_many
association: