繁体   English   中英

在Rails中验证关联的最佳方法是什么?

[英]What is the best way to validate association in Rails?

我有两个相关的模型: ApartmentLessor 我需要能够从Apartment表格创建Lessor

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

Lessor模型中:

validates :cellphone, :format => {:with => /\d{11}/}, :uniqueness => true
has_many :apartments, :dependent => :nullify

但是当我试图创建具有无效cellphone Apartment时,由于验证失败,因此不会创建Lessor ,但是“公寓”已创建。

Apartment表单中验证cellphone (可能更多)和上升错误的最佳方法是什么?

我想也许更好的解决方案是使用accepts_nested_attributes_for通过另一个形式创建嵌套模型。

有关文本版本,请参见http://railscasts.com/episodes/196-nested-model-form-part-1http://asciicasts.com/episodes/196-nested-model-form-part-1

但是,如果您想使用现有解决方案:如果您在before_*回调中返回false ,则所有后续回调和相关操作都将被取消,请参阅http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

所以我猜它会是这样的

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

这不是一个美丽的解决方案,但我认为你明白了......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM