我该如何解决这个3模型的activerecord问题?

时间:2010-05-09 20:18:52

标签: ruby-on-rails activerecord model

class student < ActiveRecord::Base
  has_many :projects

  def has_a_teacher_by_the_name_of(name)
    self.projects.any? { |project| project.teacher.exists?(:name => name) }
  end

end

class project < ActiveRecord::Base
  belongs_to :student
  has_one :teacher
end

class teacher < ActiveRecord::Base
  belongs_to :project
end

这不起作用,因为项目可能还没有教师,所以project.teacher会抛出错误:

当你没想到它时,你有一个零对象! 评估nil.exists时发生错误?

1 个答案:

答案 0 :(得分:2)

您可以添加has_many :teachers, :through => :projects或将命名范围添加到Project:

class student < ActiveRecord::Base
  has_many :projects

  def has_a_teacher_by_the_name_of(name)
    self.projects.with_teacher.any? { |project| project.teacher.exists?(:name => name) }
  end

end

class project < ActiveRecord::Base
  belongs_to :student
  has_one :teacher
  scope :with_teacher, :conditions => 'teacher_id IS NOT NULL'
end