A brief summary of Rails association options (foreign_key, primary_key)

background

I was a little addicted to changing foreign keys by associating tables with each other.

Table design

products
id
number
price
features
id
product_number
etc...

Thing you want to do

I want to associate the number of products with the product_number of features.

Commentary

code

has_one :feature, foreign_key: "number", primary_key: "product_number"
belongs_to :product, foreign_key: "product_number", primary_key: "number"

In other words, when the feature is referenced from the product side, records with the same product number and feature product_number are linked. And vice versa.

Summary

foreign_key Specify a foreign key(Specify the column of the referencing table).. The default is hogehoge_id。
primary_key Column used when referencing another table(Specify the column of the referenced table)Is specified. Id by default.

Recommended Posts

A brief summary of Rails association options (foreign_key, primary_key)
Rails: A brief summary of find, find_by, where
A brief summary of DI and DI containers
A summary of only Rails tutorial setup related
A brief summary of Bootstrap features for beginners
A brief explanation of commitAllowingStateLoss
[Rails Struggle/Rails Tutorial] Summary of Rails Tutorial Chapter 2
Summary of rails validation (for myself)
[Rails] Summary of complicated routing configurations
A brief description of JAVA dependencies
[Rails Struggle/Rails Tutorial] Summary of Heroku commands
Rails Basics of creating a new application
Rails: A little summary about data types
Summary of basic knowledge of Rails acquired by progate
[Ruby on Rails] A memorandum of layout templates
[Rails tutorial] A memorandum of "Chapter 11 Account Activation"
[Note] Summary of rails login function using devise ①
belongs_to association foreign_key option (Rails Guide personal translation)