开发者

How do i solve this 3 model activerecord problem?

开发者 https://www.devze.com 2022-12-30 04:28 出处:网络
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) }
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

This doesn't work because开发者_如何学编程 a project might not have a teacher yet, so project.teacher throws an error:

You have a nil object when you didn't expect it! The error occurred while evaluating nil.exists?


You can either add has_many :teachers, :through => :projectsor add a named scope to 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
0

精彩评论

暂无评论...
验证码 换一张
取 消