2016-12-07 24 views
3

複数の自己参照モデルを使用するコードを作成しています。結合テーブルを使用して関連付けるときに一致させることができます。複数の自己参照has_many:Rails 4の関連付け。

モデルは

User.rbのようになります。

class User < ActiveRecord::Base 
    has_many :appointments 
    has_many :students, through: :appointments 
    has_many :teachers, through: :appointments 
end 

Appointment.rb:

class Appointment < ActiveRecord::Base 
    belongs_to :student, class_name: User 
    belongs_to :teacher, class_name: User 
end 

残念ながら、レールによって生成されたクエリは次のとおりです。

SELECT "users".* FROM "users" INNER JOIN "appointments" ON "users"."id" = "appointments"."student_id" WHERE "appointments"."user_id" = $1 

それはエラーを投げる、 Appointmentにはuser_idパラメータがないためです。

私はすでにforeign_keyオプションを指定しようとしましたが、これは何もしませんでした。私はこれをエレガントに解決できる他の方法はありますか?

ありがとうございました。

+2

"... Railsで生成されたクエリ..." - どのような呼び出しですか?あなたはこの質問をするために何をしましたか?あなたは指定しませんでしたが、あなたが何をしようとしているかを一目で分かりやすくするでしょう。 – coreyward

+0

私は 'User.first.students'を試しました。 – Alex

+1

あなたは外部キーオプションを指定しようとしていますか? –

答えて

2

私はそれを解決することができました。 has_many:throughが基づいているhas_manyには、foreign_keyオプションが設定されていなければなりません。コードは

class User < ActiveRecord::Base 
    has_many :appointments_as_student, foreign_key: :student_id, class_name: Appointment 
    has_many :appointments_as_teacher, foreign_key: :teacher_id, class_name: Appointment 

    has_many :students, through: :appointments_as_teacher 
    has_many :teachers, through: :appointments_as_student 
end 

ありがとうございました。