如何在Active Record中建立多个一对多关系?

时间:2013-09-05 09:37:34

标签: sql ruby-on-rails ruby activerecord

我有两个这样的模特: Task与Student,starts_by和finished_by有两个关系,它们都是one_to_many关系。

class Task < ActiveRecord::Base
    belongs_to :started_by, class_name: Student, foreign_key: 'started_by_student_id'
    belongs_to :finished_by, class_name: Student, foreign_key: 'finished_by_student_id'
    attr_accessible :name, :id
end

class Student < ActiveRecord::Base
    attr_accessible :name, :id

has_many :started_tasks, class_name: Task
has_many :finished_tasks, class_name: Task
end

当我查询

Task.joins(:started_by).all()

Task.joins(:started_by).all()

生成的SQL看起来不错。但是当我这样做时:

Task.joins(:started_by, :finished_by).all()

生成的SQL看起来很奇怪:

  Task Load (0.5ms)  SELECT `tasks`.* FROM `tasks` INNER JOIN `students` ON `students`.`id` = `tasks`.`started_by_student_id` INNER JOIN `students` `finished_bies_tasks` ON `finished_bies_tasks`.`id` = `tasks`.`finished_by_student_id`

我不知道'finished_bies_tasks'来自何处,我该如何解决?

1 个答案:

答案 0 :(得分:0)

试试这个:

Task.find :all, :joins => [: started_by, : finished_by]