Search code examples
ruby-on-railsruby-on-rails-4mongoidmongoid4

Calling .attributes on model object avoid fileds with nil values


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!


Solution

  • 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.