[英](Rails 5.1) Self-join association gives error: no such table
It works in 5.0.6 它适用于5.0.6
The problem is within your generator. 问题出在您的发电机内。
rails g model Employees manager:references
Produces the wrong migration. 产生错误的迁移。 Read on if you want the fix.
如果您想要修复,请继续阅读。
I have a problem with self-join associations... 我有自我加入协会的问题......
class Employee < ApplicationRecord
has_many :subordinates, class_name: "Employee", foreign_key: "manager_id"
belongs_to :manager, class_name: "Employee", optional: true
end
When trying to create a "Employee" record, gives error "No such table main.managers" (at the bottom): 在尝试创建“员工”记录时,给出错误“没有这样的表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 (?, ?, ?)
The code is taken out from the RoR guide. 代码从RoR指南中删除。 How do I correct it?
我该如何纠正?
I emphasize that it is a self-join table. 我强调它是一个自联接表。 Therefore there is no "Manager" model or "managers" table.
因此,没有“经理”模型或“经理”表。
Rails version 5.1.5 Rails版本5.1.5
It's because of the migration. 这是因为迁移。 Using the command
使用命令
rails g model Employee name:string manager:references
Produces different code in 5.0.6 . 在5.0.6中生成不同的代码。 You cannot have such a migration:
你不能有这样的迁移:
create_table :employees do |t|
t.string :name
t.references :manager, foreign_key: true #mistake
t.timestamps
end
Change it to: 将其更改为:
t.references :manager, index: true
如果员工为belongs_to manager,那么您应该拥有类似Manager.employee.create的内容
在belongs_to
关联上也设置foreign_key
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.