如何在具有相同列名的两个模型之间在 Rails 中建立关联

问题描述

我有一个问题,通常我运行一个迁移并将一个名为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",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",null: false
 t.index ["company_id"],name: "index_employees_on_company_id"
end

解决方法

根据您分享的信息,我认为您需要执行以下操作: 即使您在模型中添加了 :foreign_key 指令,您也需要生成一个新的迁移以便在 DB 级别应用这些更改,在 DB 级别添加该外键后,您的架构也应该有一个新的指数。话虽如此,您可以这样做:

rails g migration <name_of_your_migration>,此命令将生成一个文件,您可以通过在更改方法中添加以下行来将外键添加到数据库:add_foreign_key :attendaces,:employees,column: :private_number

这里是 add_foreign_key 的文档。 希望这可以帮助! ?