找出一种方法来显示用户消息线程的消息,具体取决于哪些消息已被删除而不是。删除邮件时,已删除的邮件“sender_status或recipient_status”将从0更改为1。目前,要在其收件箱中显示用户消息线程列表,我使用:
e.g。
current_user = User.find(2)
current_user.message_threads
这会抓取所有带有0个发件人或收件人状态的message_thread。
class User < ActiveRecord::Base
has_many :messages
has_many :message_threads
简单易用,但我现在要做的是如何设置一些东西,使我能够从当前线程中获取具有0个发件人或收件人状态的邮件。所以,如果我要输入:
one_thread = current_user.message_threads.first
通过这个帖子,我希望能够轻松获取我需要的唯一消息。想在message_thread模型中添加一些内容,以便最终输入:
current_user.message_threads.first.messages
#or
one_thread.messages
并且只有我需要加载的邮件和忽略“1”状态的邮件。
用户模型:
class User < ActiveRecord::Base
has_many :messages
has_many :message_threads
def message_threads
MessageThread.where([ '(sender_id = ? AND sender_status = 0) OR (recipient_id = ? AND recipient_status = 0)', self.id, self.id ])
end
def messages
Message.where([ '(sender_id = ? AND sender_status = 0) OR (recipient_id = ? AND recipient_status = 0)', self.id, self.id ])
end
MessageThread模型:
class MessageThread < ActiveRecord::Base
has_many :messages
消息模型:
class Message < ActiveRecord::Base
acts_as_tree
has_one :message_thread
我尝试过尝试加入,但这对我来说效果不佳。
def messages
joins(:messages).merge( Message.where([ '(parent_id = ? AND sender_status = 0) OR (parent_id = ? AND recipient_status = 0)',self.message_id, self.message_id ]) )
end
帮助会非常感激。
亲切的问候
答案 0 :(得分:0)
我猜测问题是one_thread
正在返回一个MessageThread
对象,然后你试图通过调用self.id
来获取用户ID,但它正在被调用错误的模型。
我没有尝试过这段代码,但可能会有效:
class User < ActiveRecord::Base
def self.threads_in_inbox
message_threads.where('(sender_id = ? AND sender_status = 0) OR (recipient_id = ? AND recipient_status = 0)', self.id, self.id)
end
end
class MessageThread < ActiveRecord::Base
def self.inbox_messages
messages.where('(sender_id = ? AND sender_status = 0) OR (recipient_id = ? AND recipient_status = 0)', self.user.id, self.user.id)
# this hits the database 1 extra time however due to self.user.id
# you could change it to inbox_messages(user_id) and pass in the id manually
end
end
first_thread = current_user.threads_in_inbox.first
first_thread.inbox_messages
在您的问题中,您似乎覆盖了rails(message_threads和messages)生成的关联查询 - 不确定它是否有意,但我在上面进行了更改。
此外,我认为你可以删除重复并执行以下操作:
where('(sender_id = ?) AND (sender_status = 0 OR recipient_status = 0)', self.id)