我有以下型号:
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
创建自定义验证器无效(当我使用错误“未定义方法'部分'为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
非常感谢!
答案 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