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 recipient_id
and a sender_id
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 :sender_id
. When I change this to recipient_id
, 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| %>
<p>hi</p>
<% 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)
end
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)
end
end