Ruby on rails 避免通过seeds.rb创建重复记录?
我的Ruby on rails 避免通过seeds.rb创建重复记录?,ruby-on-rails,ruby,seeding,Ruby On Rails,Ruby,Seeding,我的seeds.rb中有以下代码,可以在我的simple Rails应用程序中创建记录 Post.create( title: "Unique Title!", body: "this is the most amazingly unique post body ever!" ) 当运行rake db:seed命令时,它显然会使用此数据为数据库进行种子设定。如何在代码中添加检查或保护,使其只输入一次,即作为唯一的?如果我重新运行rake db:seed,我不想再添加相同的条
seeds.rb中有以下代码,可以在我的simple 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,或其他创建种子版本并只运行一次的工具
其中大多数创建的种子文件与迁移文件类似一种快速防止这种情况的方法是使用find\u或\u create\u by
用法如下:
Post.find_or_create_by(title: "Unique Title!", body: "this is the most amazingly unique post body ever!")
以下是。标题“唯一标题!”提示您应该在posts
表的title
列中添加uniq索引。此外,您可能希望为模型的该属性添加唯一性验证。当您不创建一组内容作为对象数组(JSON)时,这很好。那样的话就不行了。