Currently I have a User table that has a toys_owned column that is an embedded document. How do I set to nil/modify the embedded document in my rails console? Currently it is giving me a NoMethodError when I try to set it to nil.
Note: I’m trying to avoid using the mongo shell if possible
app/models/toysOwned.rb
class ToysOwned
include Mongoid::Document
embedded_in :user, :inverse_of => :toys_owned
referenced_in :toy
end
Rails Console:
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 (some of it)
class User
include Mongoid::Document
include Mongoid::Timestamps
include ToyOwnable
...520 lines of code...
end
Try this, it should work:
If you read your code for a couple of minutes, you’ll realize that you’re doing crazy things 🙂
First, you set
uto a first oftoys_owned. Then you set this referenceutonil. This does not affect originaltoys_ownedcollection. Then you’re trying to call a method onu(which isnilat the moment and can’t fulfill your request).