无法在Mongoid中保存数组

时间:2022-02-01 13:19:27

I have a has_many relationship with another object. Because of this, Mongoid creates an attribute titled item_ids as an Array so I can conveniently save numerous ids as an array. However, whenever I attempt to save a new array it never actually saves. In my rails console I run the following code.

我与另一个对象有一个has_many关系。因此,Mongoid创建了一个名为item_ids的属性作为数组,因此我可以方便地将多个ID保存为数组。但是,每当我尝试保存新阵列时,它实际上都不会保存。在我的rails控制台中,我运行以下代码。

1.9.3p385 :035 > miss.item_ids = [1,2,3]
 => [1, 2, 3] 

1.9.3p385 :036 > miss.save
[paperclip] Saving attachments.
 => true 

1.9.3p385 :037 > miss.item_ids
 => [] 

As you can see when I save the object it returns true. However when I return to check out the item_ids I'm returned an empty array. What am I doing wrong?

正如您在保存对象时所看到的,它返回true。但是当我返回检查item_ids时,我返回了一个空数组。我究竟做错了什么?

2 个解决方案

#1


1  

You are manually creating the relation. Try miss.items << item

您正在手动创建关系。试试miss.items << item

Now miss.items should return an array of items

现在,miss.items应该返回一系列项目

#2


3  

'item_ids' isnt an attribute, is a method that runs some queries to return only the IDs of the relationed objects and appends them on an array.

'item_ids'不是属性,是一种运行某些查询以仅返回关系对象的ID并将它们附加到数组上的方法。

When you do something like miss.item_ids = [1,2,3] you are basically creating that field on the document, as you are using Mongo, it will store anything for you.

当您执行miss.item_ids = [1,2,3]之类的操作时,您基本上是在文档上创建该字段,因为您使用的是Mongo,它将为您存储任何内容。

#1


1  

You are manually creating the relation. Try miss.items << item

您正在手动创建关系。试试miss.items << item

Now miss.items should return an array of items

现在,miss.items应该返回一系列项目

#2


3  

'item_ids' isnt an attribute, is a method that runs some queries to return only the IDs of the relationed objects and appends them on an array.

'item_ids'不是属性,是一种运行某些查询以仅返回关系对象的ID并将它们附加到数组上的方法。

When you do something like miss.item_ids = [1,2,3] you are basically creating that field on the document, as you are using Mongo, it will store anything for you.

当您执行miss.item_ids = [1,2,3]之类的操作时,您基本上是在文档上创建该字段,因为您使用的是Mongo,它将为您存储任何内容。