如何在Rails Mongodb中添加新列?

时间:2019-02-22 00:27:30

标签: ruby-on-rails mongodb

我目前有以下列ID,名称,电子邮件,linkedin,公司,联系方式,招聘人员,学生,并且我想添加一个称为“已响应”的新列。我只找到有关如何向数据库中所有现有实例添加新列的答案。所以我确实尝试了这个:

db.people.update({}, {$set: {"responded": false}}, false, true)

我所有现有的实例都有一个字段:responded默认情况下设置为false。现在,当我尝试添加新人时,出现此错误:

Mongoid::Errors::UnknownAttribute in PeopleController#create



 message: Attempted to set a value for 'responded' which is not allowed on the model Person. summary: Without including Mongoid::Attributes::Dynamic in your model and the attribute does not already exist in the attributes hash, attempting to call Person#responded= 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.

1 个答案:

答案 0 :(得分:0)

MongoDB没有“列”,也没有表。您的文档带有字段。

我想您正在为模型使用MongoID,因此只需要在模型上定义字段

class Person
  include Mongoid::Document
  field :first_name, type: String
  field :middle_name, type: String
  field :last_name, type: String
  field :responded, type: Boolean # something like this
end

https://docs.mongodb.com/mongoid/current/tutorials/mongoid-documents/#fields