指向同一模型的外键

时间:2013-05-09 19:19:18

标签: ruby-on-rails ruby-on-rails-3 activerecord associations

我有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

我首先想知道在编写关联时我做错了什么或者做错了什么。理想情况下,我希望能够调用一个查询,在该查询中,我找到用户的帐户,其中用户的ID与client_idtrainer_id匹配。所以......

user.client_workouts.trainer???

1 个答案:

答案 0 :(得分: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

您也可以同时执行这两项操作,并让使用方法调用ClientWorkout上的作用域。