我有两个相关的模型:Apartment
和Lessor
。 而我需要能够从<代码>Apartment/code>上创建
In Apartment
model:
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
validates :cellphone, :format => {:with => /d{11}/}, :uniqueness => true
has_many :apartments, :dependent => :nullify
但是,当我试图创建<代码>Apartment而无效cellphone
时,Lessor
并不成立,而是建立了“部分”。
验证<条码> 移动电话代码>(而且可能更多)和在<条码>中出现错误的最佳方式是什么?