Akshay Rawat
Akshay Rawat

Reputation: 4784

Mongoid - Array assignment

I'm seeing some strange behaviour in Mongoid 2.3.4

 class Student
   has_and_belongs_to_many: teachers
 end

 class Teacher
   has_and_belongs_to_many: students
 end

Now in IRB

s = Student.first
s.teachers
=> []

s.teacher_ids = [Teacher.first.id, Teacher.last.id]
s.teacher_ids
=> [[BSON::ObjectId4f7c3300913417162c000008, BSON::ObjectId4f7c333b913417162c00000d]]

Not sure why this array is nested like that. I expected

[BSON::ObjectId4f7c3300913417162c000008, BSON::ObjectId4f7c333b913417162c00000d]

This breaks multi select fields in Rails, where the mass assignments of ids would happen like shown in IRB.

Upvotes: 0

Views: 423

Answers (1)

theTRON
theTRON

Reputation: 9649

It may have to do with the fact that you're attempting to set the teachers_ids attribute to an array of Teacher objects.

You could try these as alternatives:

s.teachers = [Teacher.first, Teacher.last]

or

s.teachers << Teacher.first
s.teachers << Teacher.last

Update:

I've just run a little test and can confirm that your method of assignment works fine in Mongoid 2.4.6 (which is just what I happened to have installed) and 2.4.8.

If for some reason you can't upgrade to Mongoid 2.4, you could also try passing the IDs in as String objects instead of as ObjectId, which is how it would be handled if this was being passed in through POST parameters.

s.teacher_ids = [Teacher.first.id.to_s, Teacher.last.id.to_s]

Upvotes: 2

Related Questions