arvindravi
arvindravi

Reputation: 53

Mongoid equivalent of ActiveRecord's `first_or_initialize`

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?

Upvotes: 2

Views: 876

Answers (2)

Zippie
Zippie

Reputation: 6088

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

Upvotes: 1

marcelowiermann
marcelowiermann

Reputation: 265

Model.find_or_initialize_by(attribute: value). You can even use multiple attributes on that call - (a1: v1, a2: v2...an: vn).

Cheers!

Upvotes: 1

Related Questions