2013-05-09 70 views
1

我有一個User模型外鍵指向同一型號

class User < ActiveRecord::Base 
    attr_accessible :email, :name 

    has_many :client_workouts 
end 

而一個ClientWorkout模型

class ClientWorkout < ActiveRecord::Base 
    attr_accessible :client_id, :trainer_id, :workout_id 

    belongs_to :client, :class_name => User, :foreign_key => 'client_id' 

    belongs_to :trainer, :class_name => User, :foreign_key => 'trainer_id' 
end 

我首先想知道什麼,或者寫的關聯,當我做錯事。理想情況下,我希望能夠在用戶的用戶身份號碼與client_idtrainer_id匹配時找到用戶的客戶端鍛鍊。所以...

user.client_workouts.trainer??? 
+0

這對我來說很好。由於您的'belongs_to'關係,您應該只能調用'client_workout.client.email'或'client_workout.trainer.email'。你真的嘗試過了嗎? – 2013-05-09 19:25:30

+0

是的,你說得對。我在做一些愚蠢的事情。謝謝。 – jason328 2013-05-09 19:26:30

+0

我更新了我的問題。 – jason328 2013-05-09 19:36:43

回答

1

這將不起作用,因爲rails假定ClientWorkout有一個user_id列。我不認爲有什麼辦法,使符合兩列的has_many關係......相反,你可以創建這樣的方法:

class User < ActiveRecord::Base 
    attr_accessible :email, :name 

    has_many :client_workouts, :foreign_key => "client_id" 

    has_many :trainer_workouts, :foreign_key => "trainer_id" 

    def client_and_trainer_workouts 
    ClientWorkouts.where("client_id = ? OR trainer_id = ?", id, id) 
    end 
end 

否則,你可以創建在ClientWorkout模型這樣的範圍:

class ClientWorkout < ActiveRecord::Base 
    attr_accessible :client_id, :trainer_id, :workout_id 

    belongs_to :client, :class_name => User, :foreign_key => 'client_id' 

    belongs_to :trainer, :class_name => User, :foreign_key => 'trainer_id' 

    scope :workouts_for_user, 
     lambda {|user| where("client_id = ? OR trainer_id = ?", user.id, user.id) } 
end 

您也可以同時執行這兩個操作,並讓use方法調用ClientWorkout上的作用域。

+0

謝謝。我希望能有一些我錯過的訣竅,但唉,沒有。 – jason328 2013-05-10 15:09:06