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

Avoid duplicate records created via seeds.rb?

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

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

当 运行 rake db:seed 命令时,它显然使用此数据为数据库播种。如何在代码中添加检查或保护,以便它只输入一次,即作为唯一输入?如果我重新运行 rake db:seed,我不想再次添加相同的条目。

试试这个:

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

希望对您有所帮助。

您可以使用 gem,例如 seed_migrationthe_gardener 或其他创建种子版本的东西,并且 运行 这些只能使用一次。

其中大部分创建类似于迁移文件的种子文件

一种快速防止这种情况的方法是使用 find_or_create_by

用法如下:

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

这是docs