How to use Rails 7.1 composite foreign keys along with Brick?
lorint opened this issue · comments
Lorin Thwaits commented
This question comes from a question raised on the Rails discussion board. Given tables created in Postgres with this code:
CREATE TABLE songs(
"songId" INTEGER,
"chartId" INTEGER,
version INTEGER,
name VARCHAR,
PRIMARY KEY ("songId", "chartId", version)
);
CREATE TABLE scores(
id SERIAL PRIMARY KEY,
"musicId" INTEGER,
level INTEGER,
version INTEGER,
instrument VARCHAR,
FOREIGN KEY ("musicId", level, version) REFERENCES songs("songId", "chartId", version)
);
INSERT INTO songs ("songId", "chartId", version, name)
VALUES (5, 3, 1, 'Requiem');
INSERT INTO songs ("songId", "chartId", version, name)
VALUES (6, 3, 1, 'Take Five');
INSERT INTO songs ("songId", "chartId", version, name)
VALUES (5, 3, 2, 'Requiem');
Your models can be created like this:
class Song < ApplicationRecord
# Primary key: songId, chartId, version
has_many :scores, query_constraints: ["musicId", "level", "version"]
end
class Score < ApplicationRecord
belongs_to :songs, query_constraints: ["musicId", "level", "version"]
end
Here is a video walkthrough showing how easy it can be using Brick to arrive upon this result:
https://github.com/lorint/brick/assets/5301131/92593ae7-75ce-4d7d-9f0a-df54ff2b0ec7
(not related is this other video about creating models for friend requests which I have linked here just as a placeholder so that Github will hold on to it.)