I have a pair of data types where every X
may have many Y
, and each Y
has at most one X
.
In the database, I'd visualized this as
CREATE TABLE xs (
id INTEGER NOT NULL PRIMARY KEY
);
CREATE TABLE ys (
id IN开发者_运维知识库TEGER NOT NULL PRIMARY KEY,
x_id INTEGER FOREIGN KEY REFERENCES xs (id) -- may be NULL
);
Using ActiveRecord, it's easy for me to that every X
has_many
Y
, but how do I express that every Y
has at most one X
? My impression that belongs_to
would normally work, but I'm not sure how it'll like the situation when x_id
is NULL
.
You're right. Y should have a belongs_to :x
.
If x_id
is not present, y.x
will return nil
.
Having a belongs_to doesn't mean that if the value is not present, everything will blow up.
精彩评论