1

I have an User model

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

  has_many :client_workouts
end

And a ClientWorkout model

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

I first want to know what or if I'm doing something wrong when writing the associations. Ideally I want to be able to call a query where I find the user's clients workouts where the user's id matches with client_id or trainer_id. So...

user.client_workouts.trainer???
4

1 回答 1

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 上的范围。

于 2013-05-09T20:35:04.553 回答