如何在Rails控制台中设置nil /修改mongoid中的嵌入数据?

时间:2012-03-31 22:10:51

标签: ruby-on-rails mongodb mongoid

目前,我有一个User表,其中toys_owned列是嵌入式文档。如何在rails控制台中设置为nil /修改嵌入文档?目前,当我尝试将其设置为NoMethodError时,它会给我一个nil

注意:我试图尽可能避免使用mongo shell

应用程序/模型/ toysOwned.rb

class ToysOwned
  include Mongoid::Document

  embedded_in :user, :inverse_of => :toys_owned
  referenced_in :toy
end

Rails控制台:

User.where(email: "john1433@aol.com").first.toys_owned
 => [#<ToysOwned _id: 7e5s72d19gb23f0001203025, toy_id: BSON::ObjectId('6g46af0g2ffchc000100003d')>]
ruby-1.9.2-p290 :049 > u = User.where(email: "john1433@aol.com").first.toys_owned.first
 => #<ToysOwned _id: 7e5s72d19gb23f0001203025, toy_id: BSON::ObjectId('6g46af0g2ffchc000100003d')>
ruby-1.9.2-p290 :051 > u = nil
 => nil 
ruby-1.9.2-p290 :052 > u.save
NoMethodError: undefined method `save' for nil:NilClass

app / models / user.rb(其中一些)

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  include ToyOwnable
  ...520 lines of code...
end

1 个答案:

答案 0 :(得分:0)

试试这个,它应该有效:

user = User.where(email: "john1433@aol.com").first
user.toys_owned.shift
user.save

如果你读了几分钟你的代码,你会发现你做的很疯狂:)

首先,您将u设置为toys_owned的第一个。然后,将此引用u设置为nil会影响原始toys_owned集合。然后,您尝试在u上调用方法(目前为nil,无法满足您的要求)。