【发布时间】:2016-05-29 18:12:42
【问题描述】:
Rails 4.2.5, Mongoid 5.1.0
我有三个模型 - Mailbox、Communication 和 Message。
mailbox.rb
class Mailbox
include Mongoid::Document
belongs_to :user
has_many :communications
end
communication.rb
class Communication
include Mongoid::Document
include Mongoid::Timestamps
include AASM
belongs_to :mailbox
has_and_belongs_to_many :messages, autosave: true
field :read_at, type: DateTime
field :box, type: String
field :touched_at, type: DateTime
field :import_thread_id, type: Integer
scope :inbox, -> { where(:box => 'inbox') }
end
message.rb
class Message
include Mongoid::Document
include Mongoid::Timestamps
attr_accessor :communication_id
has_and_belongs_to_many :communications, autosave: true
belongs_to :from_user, class_name: 'User'
belongs_to :to_user, class_name: 'User'
field :subject, type: String
field :body, type: String
field :sent_at, type: DateTime
end
我正在使用身份验证 gem devise,它可以访问指向当前登录用户的 current_user 助手。
我为满足以下条件的控制器构建了一个查询:
获取current_user 的mailbox,其communication 由box 字段过滤,其中box == 'inbox'。
它是这样构造的(并且正在工作):
current_user.mailbox.communications.where(:box => 'inbox')
当我尝试构建此查询时,我的问题出现了。我希望链接查询,以便我只获得messages 的last 消息不是来自current_user。我知道 .last 方法,它返回最近的记录。我提出了以下查询,但无法理解需要调整哪些内容才能使其正常工作:
current_user.mailbox.communications.where(:box => 'inbox').where(:messages.last.from_user => {'$ne' => current_user})
此查询产生以下结果:
undefined method 'from_user' for #<Origin::Key:0x007fd2295ff6d8>
我目前可以通过执行以下操作来完成此操作,我知道这非常低效,想立即更改:
mb = current_user.mailbox.communications.inbox
comms = mb.reject {|c| c.messages.last.from_user == current_user}
我希望将此逻辑从 ruby 转移到实际的数据库查询中。提前感谢任何在这方面为我提供帮助的人,如果这里有任何有用的信息,请告诉我。
【问题讨论】:
-
我不认为 ActiveRecord 可以为您做到这一点 - 基于聚合(最后)的条件可能太复杂了。您可能不得不求助于原始 SQL。
-
有错误吗?你写。
where(:messages.last.from_user => {'$ne' => current_user})(条件正在评论)但在current_user.mailbox.communications.reject{ |c| c.last.from_user == current_user }(条件正在交流) -
@PJSCopeland,mongo 不是 SQL 数据库
-
@ljlozano,也许您正在寻找stackoverflow.com/questions/5550253/… 和docs.mongodb.org/v3.0/reference/operator/aggregation/last(它也是聚合)。所以你的问题是如何在 mongo db 中使用聚合条件
-
@NickRoz 我很抱歉,是的,这是一个错字。我已经更新了我的问题。我现在也要看看这些链接。
标签: ruby-on-rails mongodb mongoid mongodb-query aggregation-framework