How can I make Mongoid ignore argument attributes that are not set in model the when creating/updating an object?

1.5k views Asked by At

I am trying to seed my MongoDB database via a JSON API and only want to save specific attributes for each object.

When I run the seed file, I get the following error:

Mongoid::Errors::UnknownAttribute: 
Problem:
  Attempted to set a value for 'block' which is not allowed on the model FoodTruck.
Summary:
  Without including Mongoid::Attributes::Dynamic in your model and the attribute does not already exist in the attributes hash, attempting to call FoodTruck#block= for it is not allowed. This is also triggered by passing the attribute to any method that accepts an attributes hash, and is raised instead of getting a NoMethodError.
Resolution:
  You can include Mongoid::Attributes::Dynamic if you expect to be writing values for undefined fields often.

I don't want to include Mongoid::Attributes::Dynamic because I don't want to save those specific attributes that I didn't add to my model.

I tried the two answers found here (Mongoid: How to prevent undefined fields from being created by mass assignment?), but both of them did not work for me.

How do I tell mongoid to ignore any hash keys in the argument that I did not add to the model when I try to #create or #update_attribues?

2

There are 2 answers

0
ravelinx On

Late but I think someone can benefit from it

@object.update_attributes(params.except(:block))
0
li-thy-um On

try this:

FoodTruck.create(params.as_json(only: FoodTruck.fields.keys))
foodtruck.update_attributes(params.as_json(only: FoodTruck.fields.keys))