在创建/更新对象时,如何使Mongoid忽略未在模型中设置的参数属性?

时间:2015-06-09 23:04:17

标签: ruby-on-rails mongodb mongoid

我试图通过JSON API为我的MongoDB数据库播种,只想为每个对象保存特定的属性。

当我运行种子文件时,出现以下错误:

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.

我不想包含Mongoid :: Attributes :: Dynamic,因为我不想保存那些我没有添加到模型中的特定属性。

我尝试了这里找到的两个答案(Mongoid: How to prevent undefined fields from being created by mass assignment?),但这两个答案对我都不起作用。

当我尝试#create或#update_attribues时,如何告诉mongoid忽略我没有添加到模型的参数中的任何哈希键?

2 个答案:

答案 0 :(得分:0)

迟到但我觉得有人可以从中受益

@object.update_attributes(params.except(:block))

答案 1 :(得分:-1)

试试这个:

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