0

When attributes() is called on a Mongoid model object it excludes the fields with nil values, is there a way to get all the fields irrespective of their values?

media = Media.first
media.attributes #=> ignores nil values

Also, FYI this happens when a record is created with only a few attributes, but when we create a record by assigning nil values to the remaining fields explicitly it works fine!

Any help would be highly appreciated!

Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
  • You can have callback like before_save to assign remaining attributes as nil. This is the default property of mongoid to skip missed attributes – Bijendra Feb 19 '19 at 08:45
  • 1
    [this](https://stackoverflow.com/a/8963019/10522579) may help in details – ray Feb 19 '19 at 11:21

1 Answers1

1

mongoid used to remove empty fields. If you kept some fields empty on insert, mongoid will removes them.

Use media.to_json instead for your case.

ray
  • 5,454
  • 1
  • 18
  • 40