validates_uniqueness_of field scoped to a has_one relationship
I have the following models:
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
I would like to be able to do the following in my Section
model (call_number
is a field in Section
):
validates_uniqueness_of :call_number, :scope => :term_id
This obviously doesn't work because Section
doesn't have term_id
, so how can I limit the scope to a relationship's model?
I tried creating a custom validator for Section
to no avail (doesn't work when I create a new Section
with the error "undefined method 'sections' for nil:NilClass"):
def validate_call_number
if self.term.sections.all(:conditions => ["call_number = ? AND section开发者_开发技巧s.id <> ?", self.call_number, self.id]).count > 0
self.errors[:base] << "Call number exists for term"
false
end
true
end
Thanks a lot!
Assuming your validation code is correct, why don't you simply add a check for term existence?
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
精彩评论