避免通过seeds.rb创建重复记录?

时间:2015-08-01 05:27:05

标签: ruby-on-rails ruby seeding

我在seeds.rb中有以下代码,可以在我的简单Rails应用中创建记录。

Post.create(
    title: "Unique Title!",
    body: "this is the most amazingly unique post body ever!"
  )

当运行rake db:seed命令时,它显然会使用这些数据对db进行种子处理。如何在代码中添加检查或保护措施,使其仅进入一次,即作为唯一?如果我重新运行rake db:seed,我不想再次添加相同的条目。

3 个答案:

答案 0 :(得分:4)

试试这个:

 Post.where( title: "Unique Title!",  body: "this is the most amazingly unique post body ever!").first_or_create

希望这会对你有所帮助。

答案 1 :(得分:1)

您可以使用像seed_migrationthe_gardener之类的宝石或其他创建种子版本的宝石,只运行一次。

其中大多数都会创建类似于迁移文件的种子文件

答案 2 :(得分:1)

使用find_or_create_by快速预防此问题的方法。这是docs

相关问题