Question about has_one

I have a question about regarding the use of 'has_one' in this scenario:

Schema:

User
----
id
first_name
last_name

UserMessage
----
user_id
message_id

Message
----
id

I'm not sure that it's 'has_one' that you need here. 'has_one' implies a one-to-one relationship - like Order -> Invoice.

Also, I may be wrong, but i don't think you need that joiner table. The joiner table suggests a many-to-many relationship: a message can belong to many users, a user can have many messages.

I think what you're looking for is a one-to-many relationship: A user can have many messages, a message belongs to a user.

User

Thanks for your quick response. The way that you wired it up makes sense. However, this means that the Message table must have a user_id column, and if I want to indicate that a Message has no User, then user_id must be NULL. And that would mean that if I had a lot of Messages with no User, then I'd have store quite a bit of NULL values, whereas using a joiner table, I wouldn't. Generally, I like to avoid NULLs - is there a way to design the schema/model so that I can use the joiner table? If not, I guess I'll settle and use a nullable user_id column in Message.

I'm not sure why you would want a message to not have a user, but I guess that depends on the requirements of your application.

Personally, I would favour NULLs over a joiner table in this instance - but I'd also question the relationship between User and Message if you're planning on having messages with no associated user.

Steve