0

我有以下型号:

class Section < ActiveRecord::Base
  belongs_to :course                                                          
  has_one :term, :through => :course
end

class Course < ActiveRecord::Base
  belongs_to :term
  has_many :sections
end

class Term < ActiveRecord::Base
  has_many :courses
  has_many :sections, :through => :courses
end

我希望能够在我的Section模型中执行以下操作(call_number是 中的一个字段Section):

validates_uniqueness_of :call_number, :scope => :term_id

这显然行不通,因为Section没有term_id那么我如何将范围限制为关系模型?

我尝试创建一个自定义验证器Section但无济于事(当我创建一个Section带有错误“undefined method 'sections' for nil:NilClass”的新验证器时不起作用):

def validate_call_number
  if self.term.sections.all(:conditions => ["call_number = ? AND sections.id <> ?", self.call_number, self.id]).count > 0
    self.errors[:base] << "Call number exists for term"
    false
  end
  true
end

非常感谢!

4

1 回答 1

0

假设您的验证码是正确的,您为什么不简单地添加一个术语存在检查?

def validate_call_number
  return true if self.term.nil? # add this line
  if self.term.sections.all(:conditions => ["call_number = ? AND sections.id <> ?", self.call_number, self.id]).count > 0
    self.errors[:base] << "Call number exists for term"
    false
  end
  true
end
于 2011-07-20T22:15:15.423 回答