ruby 在 rails。创建具有关联的对象时出现种子错误
ruby on rails. seed error while creating objects with association
我正在尝试创建一个任务管理原型。我创建了两个模型——类别和任务,而任务属于类别,一个类别可以包含许多任务。
class Category < ActiveRecord::Base
has_many :tasks
end
和
class Task < ActiveRecord::Base
belongs_to :category
end
然后在迁移文件中
class CreateTasks < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.string :name
t.string :note
t.references :category
t.timestamps null: false
end
end
end
和
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.string :description
t.timestamps null: false
end
end
end
我尝试播种一些数据以开始使用,这是种子文件
c1 = Category.create(name: 'Category1')
Task.create(name: 'TASK1', category_id: c1.id)
但是它给了我错误:
rake db:seed
rake aborted!
ActiveRecord::UnknownAttributeError: unknown attribute 'category_id' for Task.
我也试过以下方法
Task.create(name: 'TASK1', category: c1)
Task.create(name: 'TASK1', category: c1.id)
我得到了错误
rake db:seed
rake aborted!
ActiveRecord::AssociationTypeMismatch: Category(#70174570341620) expected, got Fixnum(#70174565126780)
但是在浏览器中,@category.id 会加载并显示(作为两位数字 33)。
我想我可能遗漏了一些明显的东西,但无法弄清楚为什么我无法从播种数据中创建与特定类别 c1 关联的任务
只需要传递对象:
c1 = Category.find_or_create_by(name: 'Category1')
我建议使用 find_or_create_by
因为不会创建两次相同的数据
Task.find_or_create_by(name: 'TASK1', category: c1)
如果不起作用,请尝试在控制台中创建相同的数据
希望对你有帮助
我正在尝试创建一个任务管理原型。我创建了两个模型——类别和任务,而任务属于类别,一个类别可以包含许多任务。
class Category < ActiveRecord::Base
has_many :tasks
end
和
class Task < ActiveRecord::Base
belongs_to :category
end
然后在迁移文件中
class CreateTasks < ActiveRecord::Migration
def change
create_table :tasks do |t|
t.string :name
t.string :note
t.references :category
t.timestamps null: false
end
end
end
和
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.string :description
t.timestamps null: false
end
end
end
我尝试播种一些数据以开始使用,这是种子文件
c1 = Category.create(name: 'Category1')
Task.create(name: 'TASK1', category_id: c1.id)
但是它给了我错误:
rake db:seed
rake aborted!
ActiveRecord::UnknownAttributeError: unknown attribute 'category_id' for Task.
我也试过以下方法
Task.create(name: 'TASK1', category: c1)
Task.create(name: 'TASK1', category: c1.id)
我得到了错误
rake db:seed
rake aborted!
ActiveRecord::AssociationTypeMismatch: Category(#70174570341620) expected, got Fixnum(#70174565126780)
但是在浏览器中,@category.id 会加载并显示(作为两位数字 33)。
我想我可能遗漏了一些明显的东西,但无法弄清楚为什么我无法从播种数据中创建与特定类别 c1 关联的任务
只需要传递对象:
c1 = Category.find_or_create_by(name: 'Category1')
我建议使用 find_or_create_by
因为不会创建两次相同的数据
Task.find_or_create_by(name: 'TASK1', category: c1)
如果不起作用,请尝试在控制台中创建相同的数据
希望对你有帮助