【问题标题】:How can I make Mongoid ignore argument attributes that are not set in model the when creating/updating an object?在创建/更新对象时,如何让 Mongoid 忽略模型中未设置的参数属性?
【发布时间】:2015-06-09 23:04:17
【问题描述】:

我正在尝试通过 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


    【解决方案1】:

    晚了,但我认为有人可以从中受益

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-13
        • 2017-12-13
        • 1970-01-01
        • 2012-11-25
        • 1970-01-01
        • 2020-10-08
        • 1970-01-01
        • 2012-04-13
        相关资源
        最近更新 更多