我有两个模型:God
和GodSkin
。
class God < ActiveRecord::Base
has_many :god_skins
end
class GodSkin < ActiveRecord::Base
belongs_to :god
end
我正在尝试创建一些种子数据,特别是God
条记录和许多子GodSkin
条记录。
God.create!(
name: 'Agni',
title: 'God of Fire',
lore: 'There are few elements as destructive or as purifying as fire. Agni, God of Fire, is
the embodiment of both of these qualities, with a head for each. Though the source of
his origin warrants debate - for there are many tales of his parentage ranging from two
simple sticks rubbed together, to the cosmic energy that made all things at the beginning
of time - Agni is a pivotal and important God with many duties to the Pantheon. He is the
twin brother to Indra, God of the Heavens and Rains and chief among warriors. Conversely,
Agni is chief among priests, acting as messenger between mortals and Gods. Every Hindu ritual
and prayer is performed in front of a fire of some kind, so Agni carries the words and sacrifices,
traveling between the Earth and the Heavens. He is welcome in every home and every hearth and
much beloved by the Faithful. Through his flames, Agni provides heat and light, but also cleanses
impurities. Smoke from his pyres create the air and hold the Heavens aloft. The sun, a source of
fire itself, brings life-giving energy to the world, and his lightning streaks the sky during storms.
For all his kindness and service, Agni has two faces. One is the face of kindness and purity,
turned towards the people and Gods. His other face, grim and resolute, guides the God of Fire,
to play his role in the cosmic cycle of creation and destruction, to burn and blacken all the
atrocities of the world to ash.',
pros: 'High Single Target Damage',
cons: 'Low Defense',
tags: 'Melee,Tank',
release_date: Date.parse('Oct 4, 2012'),
god_skins: {
god_skin: {
name: 'test',
url: 'http://www.google.com',
price: '5000'
},
god_skin: {
name: 'test2',
url: 'http://www.google.com/asdas',
price: '2300'
}
}
)
运行rake db:seed
时出现错误GodSkin expected, got an Array
。
我做错了什么?
答案 0 :(得分:4)
您需要告诉您的模型,允许accepts_nested_attributes_for :god_skins
创建其子项。然后,您只需要将密钥从god_skins
重命名为god_skins_attributes
,并且所有密钥都可以正常工作。
更新
还有一个更改,而不是传递带有重复键的哈希(!!!!!!)使用哈希数组:
god_skins_attributes: [
{
name: 'test',
url: 'http://www.google.com',
price: '5000'
},
{
name: 'test2',
url: 'http://www.google.com/asdas',
price: '2300'
}
}
另一种解决方案:
如果由于任何原因您不想使用嵌套属性,则可以在创建父级后创建子级:
God.create!(
name: 'Agni',
title: 'God of Fire',
...
).god_skins.create!([
{
name: 'test',
url: 'http://www.google.com',
price: '5000'
},
god_skin: {
name: 'test2',
url: 'http://www.google.com/asdas',
price: '2300'
}
])
)
然而,这可能会创建父级,然后在创建子级时失败,让您的父级没有子级n。为了防止这种情况,你需要在事务中包装这些调用。