2
레코드의 오류 개체에 오류가 추가되었지만 연결은 계속 저장됩니다.ActiveRecord 유효성 검사 : 유효성 검사에 실패해도 연결이 저장 됨
class Parent < ActiveRecord::Base
validate :valid_child?
#validation methods
protected
def valid_child?
@child_names = Hash.new
self.children.each do |curr_child|
if @child_names[curr_child.name].nil?
@child_names[curr_child.name] = curr_child.name
else
errors.add(:base, "child name should be unique for children associated to the parent")
end
end
end
#associations
has_and_belongs_to_many :children, :join_table => 'map__parents__children'
end
#query on rails console
@parent = Parent.find(1)
@parent.children_ids = [1, 2]
@parent.save
하위 이름은 상위의 모든 하위 항목에 대해 고유해야합니다. 일반적으로 하위 이름은 동일 할 수 있습니다. 그래서 검증은 부모와 자식 모두에게 관련이 있습니다. 여기서는 validates_associated가 작동하지 않습니다. 제발 다른 대안을 제안하십시오 –
validates_uniqueness_of에 대한 정보가 포함 된 편집 내 대답을 참조하십시오. – gregspurrier