I have a question about regarding the use of ‘has_one’ in this scenario:
Assuming business rules dictate that a Message can have at most ONE User
(let’s assume a message can be created without a user associated to it),
these are my questions:
- How would I use has_one in my model (if that’s the proper association
to use) to indicate that a message can have at most one User (without
having a nullable user_id column in Message)?
BTW, I chose to have the UserMessage mapping in its own table because if
I had user_id in the Message table, I would be forced to use the NULL
value to indicate that a Message has no User associated with it, and if
there are tons of Messages with no User, I cringe at the amount of NULL
values. (But if my logic is wrong, please let me know.)
- I know in Rails that a ‘has_one’ association means that if a Message
has_one User, then Rails expects a ‘message_id’ in the User table. Is
the schema even properly designed for Rails as there is a UserMessage
table that contains the mappings, and I would tend to want to use
‘:through’, but that option is not available in a has_one relationship.
Of course, if the correct way is indeed to use a nullable user_id
column, then this question is moot, and has_one/belongs_to is probably
the way to go.
Thanks in advance!