관련 모델이 두 개 있습니다 (Apartment
및 Lessor
). 그리고 양식에서 Lessor
을 생성 할 수 있어야합니다.Rails에서 연결의 유효성을 검사하는 가장 좋은 방법은 무엇입니까?
belongs_to :lessor
before_save :save_lessor
...
def lessor_cellphone= val
@cellphone = val
end
...
private
def save_lessor
if Lessor.exists? :cellphone => @cellphone
self.lessor = Lessor.find_by_cellphone @cellphone
else
self.create_lessor :cellphone => @cellphone
end
@cellphone = nil
end
모델 Lessor
에서 : Apartment
모델에서
validates :cellphone, :format => {:with => /\d{11}/}, :uniqueness => true
has_many :apartments, :dependent => :nullify
을하지만 잘못된 cellphone
와 Apartment
을 만들려고 할 때, Lessor
는 검증이 실패 렸기 때문에 생성되지 않지만,`아파트가 생성됩니다 .
양식에서 cellphone
(이상) 및 상승 오류의 유효성을 검사하는 가장 좋은 방법은 무엇입니까?
아파트를 연결하는 것이 가능 'accepts_nested_attributes_for'를 사용하여 휴대 전화의 레코드가 이미 존재합니까? –
물론. 새 레코드가 생성되거나 기존 레코드가 업데이트되면 아무런 변화가 없습니다. 올바른 레코드로 '빌드'해야합니다. – Vapire