固定
它适用于 5.0.6
问题出在您的发电机中。
rails g model Employees manager:references
产生错误的迁移。如果您需要修复,请继续阅读。
我对自加入协会有疑问...
class Employee < ApplicationRecord
has_many :subordinates, class_name: "Employee", foreign_key: "manager_id"
belongs_to :manager, class_name: "Employee", optional: true
end
尝试创建“员工”记录时,出现错误“没有这样的表 main.managers”(在底部):
>> Employee.create(name: "Matt")
(0.4ms) begin transaction
SQL (1.5ms) INSERT INTO "employees" ("name", "created_at", "updated_at") VALUES (?, ?, ?) [["name", "Matt"], ["created_at", "2018-02-19 16:38:21.835022"], ["updated_at", "2018-02-19 16:38:21.835022"]]
(0.2ms) rollback transaction
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: main.managers: INSERT INTO "employees" ("name", "created_at", "updated_at") VALUES (?, ?, ?)
代码摘自RoR指南。我该如何纠正它?
我强调一下,它是一个自连接表。因此没有“Manager”模型或“managers”表。
Rails 版本 5.1.5
解决方案:
是因为迁移。 使用命令
rails g model Employee name:string manager:references
在 5.0.6 中生成不同的代码。你不能有这样的迁移:
create_table :employees do |t|
t.string :name
t.references :manager, foreign_key: true #mistake
t.timestamps
end
将其更改为:
t.references :manager, index: true
最佳答案
如果 employee belongs_to manager,那么你应该有这样的 Manager.employee.create
关于ruby-on-rails - (Rails 5.1) 自连接关联给出错误 : no such table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48870537/