Is the :through association the correct way to link a joint table in Ruby on Rails


I have 3 tables named

Users table,

Messages Table and the

Message_users Table

and the Users table will be be used to store users’ info while the Messages table will be used to store the messages’ sent by users and the Message_users table will store the the message_id and the sender_id(the user who sent the message) and the receiver_id(the user to receive the message)

In the model class of Message, I have this

class Message < ApplicationRecord has_many :user, :through :message_user dependent: :destroy end

and in the User model, I have this

class User < ApplicationRecord has_many :messages, :through :message_user, dependent: :destroy end

I don’t know if this is the correct way to create the linkage between the Message model and the User model



It doesn’t seem logical to me that a message can have many users. Surely, only one user can send a message.

Maybe it would be better to use a has_many and belongs_to relationship between the models.

class User < ApplicationRecord
  has_many :messages

class Message < ApplicationRecord
  belongs_to :user

A has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model, which is probably not what you want here.