(Rails 5.1)自联接关联给出错误:没有这样的表

时间:2018-02-19 16:43:21

标签: ruby-on-rails ruby

固定

适用于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

尝试创建&#34;员工&#34;记录,给出错误&#34;没有这样的表main.managers&#34; (在底部):

>> 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指南中删除。我该如何纠正?

我强调它是一个自联接表。因此,没有&#34;经理&#34;模特或&#34;经理&#34;表

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

RoR self-join guide I'm referring to

2 个答案:

答案 0 :(得分:0)

如果员工为belongs_to manager,那么您应该拥有类似Manager.employee.create

的内容

答案 1 :(得分:0)

同时在<div class="center" appMcard> <form [formGroup]="GroupRMPM_FG"> <div formArrayName="GroupId_Name" *ngFor="let control of GroupRMPM_FG.controls.GroupId_Name.controls; let i= index"> <input type="text" pInputText [formControl]="control.controls.Group_Id_Name"/> <button pButton type="button" class="delete-btn " *ngIf="GroupRMPM_FG.controls.GroupId_Name.controls.length > 1" (click)="deleteGroup(i)" icon="fa-minus" ></button> <button pButton type="button" (click)="addNewGroup()" icon="fa-plus" class="add-btn" *ngIf="i===GroupRMPM_FG.controls.GroupId_Name.controls.length-1"></button> </div> </form> </div> 关联中设置foreign_key属性。