Reputation: 4835
I have a seed file with the following code within it:
300.times do
# create the customer
customer = Customer.create([
{customer_type_id: '1'}
])
# create an address for the customer
address = Address.create([
{city: Faker::Address.city, country: 'UK'}
])
postcode = Postcode.create([
{value: Faker::Address.uk_postcode}
])
name_number = NameNumber.create([
{value: Random.rand(495)}
])
street = Street.create([
{value: Faker::Address.street_name + " " + Faker::Address.street_suffix}
])
state = State.create([
{value: Faker::Address.uk_county}
])
This works fine. I had hoped, however, to be able to do the following:
address = Address.create([
{city: Faker::Address.city, country: 'UK'}
])
address.postcode = Postcode.create([
{value: Faker::Address.uk_postcode}
])
Where I have created the address in the first line, and I am creating the postcode for the address in the second line. This, however, generates an error.
Could anyone suggest how I can do this?
Thanks!
EDIT: As requested, the error generated is:
rake db:seed
rake aborted!
undefined method `postcode=' for #<Array:0x007f9df1f26818>
Tasks: TOP => db:seed
(See full trace by running task with --trace)
Upvotes: 0
Views: 1545
Reputation: 14983
You're passing an array to create
, which creates one object for each hash of attributes in the array and returns the resulting array of objects. Since you're only creating one object at a time, simply remove the square brackets around your hash of attributes (and even the curly braces if you want) and it should work correctly:
address = Address.create(city: Faker::Address.city, country: 'UK')
Upvotes: 1