[英]What is the best way to validate association in Rails?
I have two associated models: Apartment
and Lessor
. 我有两个相关的模型:
Apartment
和Lessor
。 And I need to be able to create Lessor
from Apartment
form. 我需要能够从
Apartment
表格创建Lessor
。
In Apartment
model: 在
Apartment
模型:
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
In Lessor
model: 在
Lessor
模型中:
validates :cellphone, :format => {:with => /\d{11}/}, :uniqueness => true
has_many :apartments, :dependent => :nullify
But when I trying to create Apartment
with invalid cellphone
, Lessor
is not created becouse validation fails, but `Apartment is created. 但是当我试图创建具有无效
cellphone
Apartment
时,由于验证失败,因此不会创建Lessor
,但是“公寓”已创建。
What is the best way to validate cellphone
(and maybe more) and rise error in the Apartment
form? 在
Apartment
表单中验证cellphone
(可能更多)和上升错误的最佳方法是什么?
I think maybe a better solution would be to use accepts_nested_attributes_for
to create a nested model through the form of an other. 我想也许更好的解决方案是使用
accepts_nested_attributes_for
通过另一个形式创建嵌套模型。
See http://railscasts.com/episodes/196-nested-model-form-part-1 or http://asciicasts.com/episodes/196-nested-model-form-part-1 for the text version. 有关文本版本,请参见http://railscasts.com/episodes/196-nested-model-form-part-1或http://asciicasts.com/episodes/196-nested-model-form-part-1 。
Nontheless, if you want to use your existing solution: If you return false
in a before_*
callback all the later callbacks and the associated action are cancelled, see http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html 但是,如果您想使用现有解决方案:如果您在
before_*
回调中返回false
,则所有后续回调和相关操作都将被取消,请参阅http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
So I guess it would be something like 所以我猜它会是这样的
def create_lessor(data)
# validate data here
return false if # data not valid
end
def save_lessor
rc = true
if Lessor.exists? :cellphone => @cellphone
self.lessor = Lessor.find_by_cellphone @cellphone
else
rc = self.create_lessor(:cellphone => @cellphone)
end
@cellphone = nil
rc # return the return code
end
It's not a beautiful solution AT ALL, but I think you get the idea... 这不是一个美丽的解决方案,但我认为你明白了......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.