gpt4 book ai didi

ruby-on-rails - Rails 5 Postgresql has_many 通过关联

转载 作者:行者123 更新时间:2023-11-29 13:22:31 24 4
gpt4 key购买 nike

在我的应用中,我有 3 个模型

class User < ApplicationRecord
has_many :specialties, class_name: "Specialty",
foreign_key:"teacher_id",
dependent: :destroy
has_many :subjects, through: :specialties, source: :subject

class Specialty < ApplicationRecord
belongs_to :teacher, class_name: "User"
belongs_to :subject, class_name: "Subject"

class Subject < ApplicationRecord
has_many :teachers, through: :specialties, source: :teacher
has_many :specialties, class_name: "Specialty",
foreign_key:"subject_id",
dependent: :destroy

在我的 rails 控制台中,以前当我使用 SQLite 时, 没有问题
user = User.first
然后 user.subjects 会返回所有用户的主题。但是,在我更改为 PostgreSQL 之后,它返回给我

ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  operator does not exist: integer = character varying
LINE 1: ...ects" INNER JOIN "specialties" ON "subjects"."id" = "special...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "subjects".* FROM "subjects" INNER JOIN "specialties" ON "subjects"."id" = "specialties"."subject_id" WHERE "specialties"."teacher_id" = $1

有什么办法可以返回 user.subjects 吗?我注意到在遵循 following 和 followed 的 rails 教程模型时没有发生此问题。 (推特模型)

谢谢

编辑,specialties 不是整数列,我会更改它并返回,非常感谢!

最佳答案

因为你的错误已经给出了提示:

HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Postgresql 对要比较的列的类型有严格的限制。

看起来你有外键 subject_idteacher_idstring 类型。所以当你比较integer类型的主键和string类型的外键时,就会出现这个错误。

您可以更改列类型以避免此错误:

change_column :specialties, :subject_id, :integer
change_column :specialties, :teacher_id, :integer

关于ruby-on-rails - Rails 5 Postgresql has_many 通过关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39199560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com