我目前正在我的应用中创建种子文件,并希望确保使用此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
仍然是必要的吗?
答案 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”的多个用户,因为如果他们之前在数据库中,您将只找到第一个用户。