I was just wondering if someone knew the mongoid equivalent of rails' activerecord-query-interface method first_or_initialize
.
How do I implement the same functionality in Mongoid?
I was just wondering if someone knew the mongoid equivalent of rails' activerecord-query-interface method first_or_initialize
.
How do I implement the same functionality in Mongoid?
Model.find_or_initialize_by(attribute: value). You can even use multiple attributes on that call - (a1: v1, a2: v2...an: vn).
Cheers!
Since Mongoid 3.1, there is a first_or_initialize method just like ActiveRecord has (and it takes multiple arguments):
Band.where(name: "Photek").first_or_initialize
Taken from: http://mongoid.org/en/mongoid/docs/querying.html#query_plus