Ruby on rails Mongoid持续性问题
我正在尝试在Rails应用程序中分配属性,但是,当我重新查询数据库时,分配的数据将消失。以下是我的模型:Ruby on rails Mongoid持续性问题,ruby-on-rails,mongodb,mongoid,Ruby On Rails,Mongodb,Mongoid,我正在尝试在Rails应用程序中分配属性,但是,当我重新查询数据库时,分配的数据将消失。以下是我的模型: class Scent include Mongoid::Document field :scentid, type: Integer field :name field :price field :category field :description field :available, type: Boolean belongs_to :order
class Scent
include Mongoid::Document
field :scentid, type: Integer
field :name
field :price
field :category
field :description
field :available, type: Boolean
belongs_to :order
embedded_in :cartitem
attr_accessible :name, :price, :category, :available
end
class Cartitem
include Mongoid::Document
field :quantity, type: Integer
embeds_one :scent
embedded_in :cart
end
以下是我正在运行的查询:
1.9.3p194 :001 > User.first.cart.cartitems.first.scent
=> nil
1.9.3p194 :060 > User.first.cart.cartitems.first.scent = Scent.first
=> #<Scent _id: 50381e2ec8bafa1710000001, _type: nil, scentid: 1, name: "gold", price"99.99", category: "fresh", description: nil, available: true, order_id: nil>
1.9.3p194 :061 > User.first.cart.cartitems.first.scent
=> nil
您没有向模型调用
save
。这是您的答案
user = User.first.cart.cartitems.first
user.scent = Scent.first
user.save!
它可以正常工作。通过单击投票选项下方的右标记,接受其中任何一个选项的答案…User.first.cart.cartitems.first.scent=scent.new会被存储,但是scent.first不会。有什么想法吗?对不起,这不行。当我再次查询User.first.cart.cartitem.first.scent时,我仍然得到了nilohh。在您的模型结构错误之前,我没有正确检查它。
scent
是嵌入文档,因此它不能属于任何其他模型。这是mongodb的基础,嵌入的文档不能在任何其他模型中引用。首先改变它,并尝试它应该工作,然后。。。
user = User.first.cart.cartitems.first
user.scent = Scent.first
user.save!