validates_uniqueness_of字段作用于has_one关系

时间:2011-07-20 21:30:19

标签: ruby-on-rails has-one validates-uniqueness-of

我有以下型号:

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_numberSection中的字段):

validates_uniqueness_of :call_number, :scope => :term_id

这显然不起作用,因为Section没有term_id所以我怎样才能将范围限制为关系的模型?

我尝试为Section创建自定义验证器无效(当我使用错误“未定义方法'部分'为nil:NilClass创建新Section时无法正常工作):

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

非常感谢!

1 个答案:

答案 0 :(得分: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