【问题标题】:How to establish an association in Rails between two models with the same column name如何在 Rails 中建立具有相同列名的两个模型之间的关联
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多