【发布时间】:2021-05-20 22:33:05
【问题描述】:
我有一个问题,通常我会运行迁移并将名为employee_id 的列添加到Attendace 模型中,然后建立关系并完成,但是对于公司的规则,我无法更改数据库。因此,要将模型与其他模型连接起来,我必须使用具有相同名称和两个模型的列,但我无法完成这种关系。我留下代码。
class Attendace < ApplicationRecord
belongs_to :employee, :class_name => "Employee", :foreign_key => "private_number"
end
class Employee < ApplicationRecord
has_many :attendaces, :class_name => "Attendace", :foreign_key => "private_number"
end
两个模型的共同列是一个名为“private_number”的字段,它是一个字符串。
出现的错误是当我尝试获取员工及其出勤率时:
2.7.2: 001> Employee.joins (: attendaces)
Traceback (most recent call last):
ActiveRecord :: StatementInvalid (PG :: UndefinedFunction: ERROR: operator does not exist: character varying = bigint)
LINE 1: ... OIN "attendaces" ON "attendaces". "Private_number" = "Empleo ...
^
HINT: No operator matches the name and type of the arguments. It may be necessary to add explicit type casts.
桌子
create_table "attendaces", force: :cascade do |t|
t.string "private_number"
t.date "date"
t.time "time"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "employees", force: :cascade do |t|
t.string "email"
t.string "name"
t.string "lastname"
t.string "position"
t.string "private_number"
t.boolean "active"
t.bigint "company_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["company_id"], name: "index_employees_on_company_id"
end
【问题讨论】:
-
你能分享你的迁移文件@Adrian Rama 吗?
-
我与数据库表共享模式。考虑到我无法更改架构。
-
两者通用的列是“private_number”。出勤和员工之间的联接,出席人数.private_number = employees.private_number。
-
感谢您的响应并分享您的架构@Adrian Rama,但我要检查的是为了正确添加外键而生成的迁移,它看起来不像您添加了外键键
-
您确定发布了实际代码吗?在错误中,“attendaces”和“Private_number”之间显然有一个空格。此外,“Private_number”以大写“P”开头的事实似乎表明发布的 doe 与您的代码库中的内容不匹配。
标签: ruby-on-rails ruby join pg