2

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?

arvindravi
  • 53
  • 1
  • 4

2 Answers2

1

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

Cheers!

marcelowiermann
  • 265
  • 2
  • 5
1

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

Zippie
  • 6,018
  • 6
  • 31
  • 46