Rails4嵌套模型验证失败

时间:2013-09-17 07:52:26

标签: validation ruby-on-rails-4 nested-forms

我有一个模型Profile,属于Person and Person有很多电子邮件。有趣的是,当我创建Profile(基于nested_form gem的一个大表单)并填写错误的电子邮件时,单击“Create”后验证将返回错误消息,但是当我再次单击“Create”而没有任何形式更改时我得到“找不到身份证= 1002的人身份ID为ID =”。以某种方式创建没有配置文件的人。如果关联的电子邮件错误,我不想创建Person。我正在尝试不同的验证以避免此错误,例如validates_associated等。这是我的代码:

class Profile < ActiveRecord::Base

  belongs_to :contact_person
  belongs_to :person, validate: true    

  accepts_nested_attributes_for :person, allow_destroy: true

  validates_presence_of  :person   

  delegate :gender, :title, :first_name, :last_name, :birthday, :place_of_birth, :name, :company, :company_name, :age, :web_profiles, :main_email, :main_phone_number, :main_address, :main_web_profile, to: :person  
end

class Person < ActiveRecord::Base

  GENDER = { male: 2, female: 1}
  TITLE = { dr: 0, prof: 1, prof_dr: 2 }

  has_one     :profile
  has_many    :emails, validate: true,                class_name: 'ContactType::Email'
  has_many    :phone_numbers, validate: true,         class_name: "ContactType::PhoneNumber"
  has_many    :web_profiles, validate: true,          class_name: "ContactType::WebProfile"

  validates_presence_of :first_name, :last_name  

  accepts_nested_attributes_for :emails, allow_destroy: true
  accepts_nested_attributes_for :phone_numbers, allow_destroy: true
  accepts_nested_attributes_for :web_profiles, allow_destroy: true
end

class ContactType::Email < ActiveRecord::Base

  EMAIL_TYPE = { work: 0, private: 1, other: 2 }

  belongs_to :person, validate: true  

  validates_format_of :address, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, message: I18n.t('simple_form.error.address_email')

  def email_type
    EMAIL_TYPE.key(read_attribute(:email_type))
  end

  def email_type=(t)
    write_attribute(:email_type, EMAIL_TYPE[t.to_sym])
  end

end

提前感谢任何建议。

0 个答案:

没有答案