i got a simple messaging system running between two users.
the user who is creating a conversation
gets a record i can access via User.find(sender_id).conversation.last
, the recipient however gets a => nil if i try to access User.find(recipient_id).conversation.last
(ofc i replaced recipient_id and sender_id with the actual id).
However, both user get the messages associated with the conversation and can chat. I am using foreign keys according to the tutorial of Dana Mulder on Medium. i think this is weird because i expect that both users ( the reciever and the sender ) should be able to access the record for the conversation they are into. is there a way to achieve that?
my models:
User.rb
has_many :conversations, :foreign_key => :sender_id, dependent: :destroy
has_many :messages, through: :conversations
Conversation.rb
belongs_to :sender, :foreign_key => :sender_id, class_name: 'User'
belongs_to :recipient, :foreign_key => :recipient_id, class_name: 'User'
has_many :messages, dependent: :destroy
Message.rb
belongs_to :conversation
belongs_to :user
the conversations controller:
conversations_controller.rb
def create
if Conversation.between(params[:sender_id],params[:recipient_id]).present?
@conversation = Conversation.between(params[:sender_id], params[:recipient_id]).first
else
@conversation = Conversation.create!(conversation_params)
end
redirect_to conversation_messages_path(@conversation)
end
do you have an idea how to make the conversation accessible for both users? (it is accessible but not in the way i need it to).
thanks in advance!