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

标签 ruby-on-rails ruby postgresql activerecord

在我的应用中,我有 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/

相关文章:

ruby-on-rails - Rails + Devise,具有嵌套属性的注册表单不创建关联记录

ruby-on-rails - NameError:升级到 rails3 时未初始化的常量 Test::Unit::AssertionFailedError

postgresql 根据其他列的值计算列的最小值

ruby - 按相似性对字符串进行分组

javascript - 嵌套 Rails 模型 - 在创建时忽略 child_index

database - 使用存储过程模拟 postgresql

postgresql - postgres SQL 状态 : 22P02

css - Rails 图像标记助手

ruby-on-rails - 如何在 Rails 模型中为类方法起别名?

ruby - 崇高文本 3 : Ruby syntax highlighting bug