开发者

validates_uniqueness_of can't check on unsaved data?

I have a model called 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_S开发者_JAVA技巧UBJECT_CHOICE}

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

the uniqueness validator don't work on unsaved data? How can I solve it?

Solution: Instead of validating in itself, the parent object should do the validation:

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


Validations do not work like that. They are dynamic by nature. If you want database constraints, you have to specify it in your migrations. For instance, a :uniq => true would make sure that a value is unique in your model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜