Reputation: 2284
What is mongoid/ruby syntax for:
I would like to query for a Parent
including all Children
(eagerly) searching by some unique Child
attribute (not the _id
).
class Parent
include Mongoid::Document
field :first_name, :type => String
field :last_name, :type => String
has_many :children, :class_name => 'Child', :inverse_of => :parent
end
class Child
include Mongoid::Document
field :first_name, :type => String
field :last_name, :type => String
belongs_to :parent, :class_name => 'Parent', :inverse_of => :children
end
in SQL, I would write
SELECT p.*, c.*
FROM Parent p
INNER JOIN Child c
ON c.parent_id = p._id
WHERE EXISTS (
SELECT 1 FROM Child c2 WHERE c2.first_name = 'Aaron' AND c2.parent_id = p._id
);
Upvotes: 2
Views: 641
Reputation: 5213
Try this
children = Child.where(:first_name => "Aaron")
children.each do |child|
parent = child.parent
end
if you need only publication details based on above condition you can run this
Parent.includes(:child).where('child.first_name' => "Aaron")
but for children you have to again make the query.
Upvotes: 1