So I have a two models like this
class ModelParent
include Mongoid::Document
field :name, :type => String
has_one :model_child
end
class ModelChild
include Mongoid::Document
field :name, :type => String
belongs_to :model_parent
end
Assuming I have an persisted instance of ModelParent called mp in the rails console
mc = mp.create_model_child(:name=>"child")
and then do
mp.model_child
it returns a valid object
however if I search for it like this:
ModelParent.where(:model_child.ne => nil).length
it returns 0
I've tried creating model_child and then assigning it, also using build_model_child(), and each method shows model_child is clearly in the parent, however the query for not nil (.ne) fails to find all ModelParents with children.
What am I doing wrong?
Update:
Answering my own question. I'm still unsure why the :model_child.ne => nil is not working, however...
I solved the problem by coding something like this:
def self.with_child
user_ids = ModelChild.all.only(:model_parent_id).map(&:model_parent_id)
return ModelParent.where(:_id.in => user_ids).all
end