0

我有一个种子文件,其中包含以下代码:

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}
  ])

这工作正常。然而,我曾希望能够做到以下几点:

address = Address.create([
  {city: Faker::Address.city, country: 'UK'}
])
address.postcode = Postcode.create([
  {value: Faker::Address.uk_postcode}
])

我在第一行中创建了地址,我正在为第二行中的地址创建邮政编码。但是,这会产生错误。

谁能建议我怎么做?

谢谢!

编辑:根据要求,生成的错误是:

rake db:seed
rake aborted!
undefined method `postcode=' for #<Array:0x007f9df1f26818>

Tasks: TOP => db:seed
(See full trace by running task with --trace)
4

1 回答 1

1

您将一个数组传递给create,它为数组中的每个属性散列创建一个对象,并返回生成的对象数组。由于您一次只创建一个对象,只需删除属性散列周围的方括号(如果需要,甚至可以删除花括号),它应该可以正常工作:

address = Address.create(city: Faker::Address.city, country: 'UK')
于 2012-07-21T20:26:05.613 回答