Rails - 通过关联使用has_many播种数据?

时间:2012-07-21 20:05:21

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

我有一个包含以下代码的种子文件:

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)

1 个答案:

答案 0 :(得分:1)

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

address = Address.create(city: Faker::Address.city, country: 'UK')