使用find_or_create_by为数据库设定种子

时间:2015-04-22 02:30:38

标签: ruby-on-rails database activerecord model

我目前正在我的应用中创建种子文件,并希望确保使用此post中建议的find_or_create_by不会创建重复项。我使用find_or_create_by_name但收到此错误:

NoMethodError: undefined method `find_or_create_by_name' for #<Class:0x007fa9680cb688>

这就是我在种子文件中使用的

Genre.find_or_create_by_name([
    {name: "Alternative"}, 
    {name: "Country"}, 
    {name: "Electronic"}
    ])

也值得一提。如果我有一个模型名称的唯一性验证器,find_or_create_by仍然是必要的吗?

2 个答案:

答案 0 :(得分:5)

较新版本的Rails使用略有不同的语法:

Genre.find_or_create_by(name: 'Alternative')

find_or_create_by不支持一次添加多条记录,因此您必须构建一个哈希数组并调用find_or_create_by多个时间:

hashes = [
  {name: "Alternative"}, 
  {name: "Country"}, 
  {name: "Electronic"}
]

hashes.each do |hash|
  Genre.find_or_create_by(hash)
end

答案 1 :(得分:0)

或者,您可以使用以下内容:

User.where(name: "Alice").first_or_create

这将返回名为“Alice”的第一个用户,如果没有,则会创建并返回名为“Alice”的新用户。

这并不意味着您不能拥有名为“Alice”的多个用户,因为如果他们之前在数据库中,您将只找到第一个用户。