thank_you
thank_you

Reputation: 11107

Can't save array in Mongoid

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.

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?

Upvotes: 1

Views: 1183

Answers (2)

Jason Prins
Jason Prins

Reputation: 136

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

Now miss.items should return an array of items

Upvotes: 1

yogodoshi
yogodoshi

Reputation: 131

'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.

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.

Upvotes: 3

Related Questions