我有一个模型 Profile,它属于 Person 并且 Person 有很多电子邮件。有趣的是,当我创建个人资料(基于nested_form gem 的一个大表单)并填写错误的电子邮件时,单击“创建”后验证将返回错误消息,但是当我再次单击“创建”时,表单没有任何更改我得到“找不到 ID = 1002 的个人资料 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
提前感谢您的任何建议。