我有一个包含一些现有类别的应用程序,并希望向其添加更多类别。由于引用了一些其他类别,我想我会将其添加到种子文件中。
我不想覆盖任何现有的类别,所以我使用 find_or_create 方法添加一个:name
和:category_parent_id
基于这个问题。
所以我将以下内容添加到我的种子文件中
categories = Category.find_or_create_by_name_and_category_parent_id(
{name: "TV", category_parent_id: 2},
{name: "Oven", category_parent_id: 2},
{name: "Fridge", category_parent_id: 2},
{name: "Microwave", category_parent_id: 2},
{name: "Toaster", category_parent_id: 2}
)
如果在类别表中没有匹配条目时在控制台中运行它,我得到的输出如下
Category Load (0.5ms) SELECT "categories".* FROM "categories" WHERE "categories"."name" = 'Microwave' AND "categories"."category_parent_id" = 2 LIMIT 1
(0.3ms) BEGIN
Category Exists (0.6ms) SELECT 1 AS one FROM "categories" WHERE "categories"."name" = 'Microwave' LIMIT 1
SQL (18.8ms) INSERT INTO "categories" ("category_parent_id", "category_type", "created_at", "name", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["category_parent_id", 2], ["category_type", nil], ["created_at", Fri, 15 Mar 2013 14:41:53 EST +11:00], ["name", "Microwave"], ["updated_at", Fri, 15 Mar 2013 14:41:53 EST +11:00]]
(0.8ms) COMMIT
=> #<Category id: 31, name: "Microwave", created_at: "2013-03-15 03:41:53", updated_at: "2013-03-15 03:41:53", category_type: nil, category_parent_id: 2>
所以这只从种子文件中添加了 1 个条目。如果这些都不存在,为什么不全部输入?
谢谢你的帮助。:)
感谢 JIM 和 JOHN 的回答
感谢 Jim 和 John,我能够更改我的代码以使用以下解决方案。
category_options = [
{name: "TV", category_parent_id: 2},
{name: "Oven", category_parent_id: 2},
{name: "Fridge", category_parent_id: 2},
{name: "Microwave", category_parent_id: 2},
{name: "Toaster", category_parent_id: 2}
]
categories = category_options.each do |c|
Category.find_or_create_by_name_and_category_parent_id(c)
end