Search code examples
ruby-on-railsmongoidfaker

Is there a way to seed hashes using the Faker gem?


I am trying to seed some data but I have a field that takes in a hash. When I do the following

50.times do 
  Event.create(
    name: Faker::Internet.name,
    data: Faker::Lorem.words(4),
    uri:  Faker::Internet.url
    )
end
events = Event.all

I get an error saying that data is being seeded as an array since it's a hash field. Is there a work around this?

rake aborted!
Mongoid::Errors::InvalidValue: 
Problem:
  Value of type Array cannot be written to a field of type Hash
Summary:
  Tried to set a value of type Array to a field of type Hash

I tried doing the following:

data: Faker::Lorem.words(4).to_h

but it doesn't seem to work.


Solution

  • You could do

    Event.create(
      name: Faker::Internet.name,
      data: Hash[*Faker::Lorem.words(4)],
      uri:  Faker::Internet.url
    )