2013-05-09 75 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