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

问题描述 投票:2回答:2

我试图通过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忽略我没有添加到模型的参数中的任何哈希键?

ruby-on-rails mongodb mongoid
2个回答
0
投票

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

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

-1
投票

试试这个:

FoodTruck.create(params.as_json(only: FoodTruck.fields.keys))
foodtruck.update_attributes(params.as_json(only: FoodTruck.fields.keys))
© www.soinside.com 2019 - 2024. All rights reserved.