【问题标题】:Foreign Keys pointing to same Model指向同一模型的外键
【发布时间】:2013-05-09 19:19:18
【问题描述】:

我有一个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_id 或trainer_id 匹配。所以...

user.client_workouts.trainer???

【问题讨论】:

  • 对我来说看起来不错。由于您的belongs_to 关系,您应该只能致电client_workout.client.email 或client_workout.trainer.email。你真的试过了吗?
  • 是的,你是对的。我在做一些愚蠢的事情。谢谢。
  • 我更新了我的问题。

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


【解决方案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 上的范围。

【讨论】:

  • 谢谢。我希望我错过了一些技巧,但可惜没有。
猜你喜欢
  • 2016-12-07
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
  • 2017-01-09
相关资源
最近更新 更多