【问题标题】:validates_uniqueness_of field scoped to a has_one relationshipvalidates_uniqueness_of 范围为 has_one 关系的字段
【发布时间】:2011-07-20 21:30:19
【问题描述】:

我有以下型号:

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 创建一个自定义验证器,但无济于事(当我创建一个新的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

非常感谢!

【问题讨论】:

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


    【解决方案1】:

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

    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
    

    【讨论】:

    • term 在保存之前似乎总是nil。我认为这是因为term 只能通过关系提供给section
    • @zsalzbank 这应该取决于您是否为该部分分配了Course。如果您已将 Course 分配给 Section 并且 Course 具有 Term self.term 不应为 nil,即使该部分实例是新记录。
    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2020-04-17
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多