MongoidEmbedFinder
This simple gem lets you find embedded documents easily. It does not instantiate parent record with a whole bunch of embedded documents. Instead it instantiates found embedded documents first and then sets parent association.
At the moment it allows you to find only one embedded document and assumes relation embeds_many
.
Installation
Add this line to your application's Gemfile:
gem 'mongoid_embed_finder'
And then execute:
$ bundle
Or install it yourself as:
$ gem install mongoid_embed_finder
Usage
Let's say that you have defined two classes as follows:
class Door
include Mongoid::Document
embedded_in :car
end
class Car
include Mongoid::Document
embeds_many :doors
field :name, type: String
end
Now you can easily retrieve instances of Door
class using finder
:
finder = MongoidEmbedFinder::Runner.new(Door, :car)
# first argument is embedded class
# second is name of the association to the parent
If you have door_id
at your hands:
finder.first(id: door_id)
# => instance of Door class or nil in case not found
If you have door_id
and car_id
as well, you can narrow scope of cars:
finder.first(id: door_id, parent: { id: car_id })
# => instance of Door class or nil in case not found
In general you can basically pass any set of child's and parent's attributes.
Latter group should be passed under parent
key. Those attributes are passed down to Mongoid::Criteria
.
Warning!
If your embedded object has other referenced entities they will not be loaded.
By default no parent's attributes are set except its primary key. It is deliberate to limit
amount of returned data.
To retrieve parent's attributes list them under parent.include_fields
as follows:
finder.first(id: door_id, parent: { id: car_id, include_fields: [:name] })
Contributing
- Fork it ( https://github.com/growthrepublic/mongoid_embed_finder/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request