Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define an array field when using create in mongoid?

Tags:

mongoid

I'm trying to create a seed file to populate my mongo database. The following syntax creates a nil value when I try to define the array field value. I'm using mongoid v3.0.9. What am I doing wrong?

These following examples do not work when I put them in the seed file:

User.create(name:'name', test_array_field:'[123,123]')
User.create(name:'name', test_array_field:[123,123])
User.create(name:'name', test_array_field:[123,123].to_a)

I've defined the field in my class like so:

field :test_array_field, type: Array
like image 518
perseverance Avatar asked Aug 27 '26 02:08

perseverance


1 Answers

Your second syntax works for me.

class User
  field :roles, type: Array, default: []
end

u = User.create roles: ['superadmin']
u.new_record? # => false
u.roles # => ["superadmin"]
like image 198
Sergio Tulentsev Avatar answered Aug 29 '26 12:08

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!