Rails 101 seed档 - xinzhongliang/xinzhongliang.github.io GitHub Wiki
Rails 101 seed档:20个groups各30个posts
Rails 101 练习时使用的seed档。 把下列内容放进seeds.rb文档里。
puts 'Hello World!'
puts "这个种子档会自动建立一个帐号, 并且创建20个 groups, 每个 group 各 30 个 posts"
create_account = User.create([email: '[email protected]', password: '12345678', password_confirmation: '12345678'])
create_groups = for i in 1..20 do
Group.create!([title: "Group no.#{i}", description: "这是用种子建立的第 #{i} 个讨论版", user_id: "1"])
for k in 1..30 do
Post.create!([group_id: "#{i}",content: "这是用种子建立的第 #{k} 个留言", user_id: "1"])
end
end
需要生成大量数据的时候,这样的写法更简洁一点:
Group_demo = [“title1”,“description1”],[“title2”,“description2”],[“title3”,“description3”],[“title4”,“description4”],[“title5”,“description5”](/xinzhongliang/xinzhongliang.github.io/wiki/“title1”,“description1”],[“title2”,“description2”],[“title3”,“description3”],[“title4”,“description4”],[“title5”,“description5”)
create_groups = for i in 1..40 do
groups_test=jobs_demo[rand(0..4)]
Group.create!([title:groups_test[0],description:groups_test[1]])
end
这个函数式是新建40个group,数据从Group_demo的五组数据里面随机选择