ruby on rails - validates_uniqueness_of field scoped to a has_one relationship -


i have 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 able following in section model (call_number field in section):

validates_uniqueness_of :call_number, :scope => :term_id 

this doesn't work because section doesn't have term_id, so how can limit scope relationship's model?

i tried creating custom validator section no avail (doesn't work when create new section error "undefined method 'sections' nil:nilclass"):

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

thanks lot!

assuming validation code correct, why don't add check term existence?

def validate_call_number   return true if self.term.nil? # add line   if self.term.sections.all(:conditions => ["call_number = ? , sections.id <> ?", self.call_number, self.id]).count > 0     self.errors[:base] << "call number exists term"     false   end   true end 

Comments

Popular posts from this blog

actionscript 3 - TweenLite does not work with object -

php - How can I edit my code to echo the data of child's element where my search term was found in, in XMLReader? -

c# - Global Variables vs. ASP.NET Session State -