How to select parent record with specific condition on child record?
-
27-06-2021 - |
Frage
I am building an application with Rails 3 and MongoDB(mongoid adapter). I am struggling to find the parent records with specific condition in child records.
class Food
include Mongoid::Document
has_many :subscriptions, as: :subscribable
end
class Subscription
include Mongoid::Document
field :subscriber_id
belongs_to :subscribable, polymorphic: true
belongs_to :subscriber
end
I want to select Foods that a specific user has not subscribed.
Here is my query that does not works.
Food.not_in('subscriptions.subscriber_id' => [User.first.id])
But it returns all the foods. What is wrong with my query?
Any help is appreciated.
Thanks
Lösung
Such query will not work in Mongoid. The following query would need to join two collections but MongoDB does not have the concept of joining. Therefore when you query you can only use the fields of the documents in the collection you are querying - in this case it's foods
collection (most likely).
If you wan't to query food based on subscriptions I would recommend embedding the Subscription
in the Food. As described here.