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时发生错误?
答案 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