validates_uniqueness_of无法检查未保存的数据?

时间:2011-03-21 16:45:59

标签: ruby-on-rails ruby-on-rails-3

我有一个名为Science Subject Choice

的模型
class ScienceSubjectChoice < SubjectChoice
    belongs_to :subject
    belongs_to :subject_preference
    validates_associated :subject
    validates_associated :subject_preference
        #TODO: validation
    validates :priority, :presence => true, :numericality => true, :inclusion => {:in => 1..SubjectPreference::MAX_SCIENCE_SUBJECT_CHOICE}

    validates_uniqueness_of :subject_id, :scope => :subject_preference_id
    validates_uniqueness_of :priority, :scope => :subject_preference_id
end

唯一性验证器不适用于未保存的数据? 我该如何解决?

解决方案: 父对象应该进行验证,而不是自己进行验证:

def validate_science_subject_choices_uniqueness
    if science_subject_choices.map(&:priority) != science_subject_choices.map(&:priority).uniq
      errors[:base] << "Duplicated priority in science subject"
    end
end

1 个答案:

答案 0 :(得分:0)

验证不起作用。它们本质上是动态的。如果需要数据库约束,则必须在迁移中指定它。例如,a:uniq =&gt; true将确保模型中的值是唯一的。