Reputation: 2262
I have Projelements
, which are like:
Milestone
Task
Each Projelement
can have one or more embedded Comments
(thanks to Mongoid
).
I want to be able to easily say:
Give me a list of Projelements
sorted by when they were last updated
Where last_updated
for a Projelement
is the larger of:
this_projelement.updated_at
ORif this_projelement.comments.count > 0 then this_projelement.comments.last.updated_at
I can create a Projelement
class method last_updated_at
with the above logic.
But what I really want to end up with is doing a query of my Projelements
, retrieving the last updated Projelement
using the above logic, in the same way as you'd do a query using an attribute.
Previously, I tried using an attribute-only approach:
Tried using the updated_at
attribute: this timestamp is updated if you update a Projelement
's attributes, but is not updated if you update the embedded Comments
. So I could manually update this_projelement.updated_at
whenever a Comment
is added. But the design feels brittle.
Also thought about having a separate attribute (e.g. last_updated_at
) so that existing semantics of updated_at
are not messed with. But design also feels brittle.
What would be the Rails way?
Upvotes: 1
Views: 136
Reputation: 46914
With MongoDB, there are no solution to order by some embedded document field.
In your case, the solution to do a callback before_save in your Comment and update an attribute in your parent document seem the most reasonnable technic.
Upvotes: 2