根据哪些消息线程已被删除或未被删除,在为用户显示消息的方法方面遇到了一些困难。删除邮件后,已删除的邮件"sender_status或receivent_status"将从0更改为1。目前在收件箱中显示用户消息线程的列表,我使用:
例如
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
消息线程模型:
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
如有帮助,不胜感激。
亲切问候
我猜问题是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)