3
votes

Using Mongoid (3.1.6) I have a collection with the following fields:

field :project, type: String
field :date_hierarchy, type: Hash, default: {year: 0, semester: 0, quarter: 0, month: 0, day: 0}

I want to find a document with project: "1", date_hierarchy: {year: 2013, semester:2, quarter: 4, month: 11, day: 12} and if the document is not found the i want it to be created How can I do this? I have tried these and non of them work

MyModel.where(:project=>"1", "date_hierarchy.year"=>2013, "date_hierarchy.semester"=>2, "date_hierarchy.quarter"=>4, "date_hierarchy.month"=>11, "date_hierarchy.day"=>25).first_or_create!

MyModel.where(:project=>"1", "date_hierarchy.year"=>2013, "date_hierarchy.semester"=>2, "date_hierarchy.quarter"=>4, "date_hierarchy.month"=>11, "date_hierarchy.day"=>25).find_or_create_by("date_hierarchy.year"=>2013, "date_hierarchy.semester"=>2, "date_hierarchy.quarter"=>4, "date_hierarchy.month"=>11, "date_hierarchy.day"=>25).
1

1 Answers

3
votes

You need pass the date_hierarchy value as a hash, as you would pass to new() or create():

MyModel.find_or_create_by({
  project: '1',
  date_hierarchy: {year: 2013, semester: 2, quarter: 4, month: 11, day: 25}
})