Michael Lombardo Michael Lombardo - 1 month ago 4x
HTML Question

Cant list conversations for current_user that is recipient of the conversation

I have a problem listing one of my models.. I am following the tutorial http://josephndungu.com/tutorials/gmail-like-chat-application-in-ruby-on-rails
In this tutorial you make a conversation that has a

and a
these are both foreign keys to the conversation table. the current_user is set on either recipient or sender when the conversation is made.

-I can only list the current_user.conversations when the current_user is a sender.
-When i try with a current_user that is a recipient I get no result.

-Figured out that in my user model I have a has_many conversations with a foreign_key
. When I change this to
, then only the current_user that is a recipient can list conversations.

-With this I assume that I need to have two foreign keys referencing the same user? What can I do to get conversations to list for both current_users?

User.rb "model"

has_many :conversations, class_name: "Conversation", :foreign_key => :sender_id

listing conversation for current_user:

<% current_user.conversations.each do |conversation| %>

<% end %>

Conversation.rb "model"

class Conversation < ActiveRecord::Base

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

validates_uniqueness_of :sender_id, :scope => :recipient_id

scope :involving, -> (user) do
where("conversations.sender_id =? OR conversations.recipient_id =?",user.id,user.id)

scope :between, -> (sender_id,recipient_id) do
where("(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id)



The problem is that in your User.rb model you are saying that The conversations of this user are those whose sender_id is this user. That is the reason why when you use current_user.conversations you only get those records where sender_id is the current user.

I would do the following in your User.rb model:

has_many :conversations_started, class_name: "Conversation", :foreign_key => :sender_id
has_many :conversations_continued, class_name: "Conversation", :foreign_key => :recipient_id

This way you would be able to invoke:




However, if you want to be able to list them all, you will need to define an additional method in your User.rb model:

def conversations
  conversations_started + conversations_continued

If a user can start a conversation with itself, I would add .uniq at the end of the conversations method