I have 3 models as listed below:
Model
class Message < ApplicationRecord
belongs_to :sender, class_name: "User"
belongs_to :recipient, class_name: "User"
belongs_to :conversation
end
class Conversation < ApplicationRecord
has_many :messages
end
class User < ApplicationRecord
has_many :recieved_messages, class_name: "Message", foreign_key: "recipient_id"
has_many :sent_messages, class_name: "Message", foreign_key: "sender_id"
end
I tried this in user.rb:
def get_user_conversations
user_conversations = []
self.recieved_messages.each do |message|
user_conversations << message.conversation
end
self.sent_messages.each do |message|
user_conversations << message.conversation
end
end
But I got messages instead of conversations that I wanted.
And I tried in rails console:
u1 = User.first
u1.sent_messages[0].conversation
This time got the conversation.
Here are is my question:
Why does user_conversations << message.conversation
not work, but u1.sent_messages[0].conversation
does?
What is the right way to get the conversations at this situation?
Thanks.
Maybe this way?
ids = current_user.sent_messages.pluck(:conversation_id)
Conversation.find(ids)
I don't know, try to reload console. Maybe you should explicitly return user_conversations
in the end of method.
You can use Conversation.joins(:messages).where("messages.recipient_id = ? OR messages.sender_id = ?", current_user.id, current_user.id).distinct
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments