2016-08-29 163 views
1

Rails的5 PostgreSQL的的has_many,我這裏有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? 我注意到,在遵循和遵循rails教程模型時沒有發生這個問題。 (Twitter的模型)

謝謝

編輯,特色菜是不是一個整數列,我要改變它,回來非常感謝!

+0

'「特色菜」,「subject_id」「 - 這是一個整數列? – dp7

+0

哦,它不是! ,我下班後要把它放好。謝謝!! – Holmes

+0

't.string:subject_id' - 它是** String **類型,外鍵的類型應與您的主鍵相同,否則在比較它們時會出現類型轉換錯誤 – dp7

回答

1

由於您的錯誤已經給提示:

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

PostgreSQL是嚴密的關於類型的列進行比較。

看起來你有外鍵subject_id,teacher_id字符串類型。因此,當您比較類型爲整數的主鍵與類型的外鍵字符串時,會出現此錯誤。

您可以更改列類型,以避免這個錯誤:

change_column :specialties, :subject_id, :integer 
change_column :specialties, :teacher_id, :integer 
+0

我正在尋找替代解決方案。我的一些模型使用主鍵是字符串,有些使用整數。爲了實現這兩個目標,我將我的association_id列設置爲一個字符串,但我遇到了這個錯誤。 – BananaNeil

相關問題