使用 find_or_create_by 为数据库播种
Using find_or_create_by to seed a database
我目前正在我的应用程序中创建一个种子文件,并希望确保没有使用此 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
?
较新版本的 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
或者,您可以使用这样的东西:
User.where(name: "Alice").first_or_create
这将 return 第一个名为 "Alice" 的用户,如果没有,它将创建 return 一个名为 "Alice" 的新用户].
这并不意味着您不能有多个名为 "Alice" 的用户,因为如果他们之前在数据库中,您将只能找到第一个。
我目前正在我的应用程序中创建一个种子文件,并希望确保没有使用此 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
?
较新版本的 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
或者,您可以使用这样的东西:
User.where(name: "Alice").first_or_create
这将 return 第一个名为 "Alice" 的用户,如果没有,它将创建 return 一个名为 "Alice" 的新用户].
这并不意味着您不能有多个名为 "Alice" 的用户,因为如果他们之前在数据库中,您将只能找到第一个。