我有一个具有 3 个虚拟属性(phoneAreaCode、phonePrefix 和 phoneSuffix)的表单,将电话号码分成多个段,这些段连接在一起并作为 phoneNum 保存到数据库中。
当用户去更新他们的个人资料时,大部分字段都会被填写,但虚拟字段不会。我尝试使用我认为是吸气剂的东西来使其工作,但我无法弄清楚我错过了什么。关于这一点,我正在使用具有来自第二个模型的地址属性的嵌套表单,但是,当这些属性为 nil 时,表单字段根本不会显示在更新视图中。即使它们为零,有没有办法让它们显示?嵌套的表单属性出现在注册视图中,并且注册和更新视图都从布局呈现相同的表单。模型如下。
class User < ActiveRecord::Base
attr_accessor :phoneAreaCode, :phonePrefix, :phoneSuffix
attr_accessible :MOS, :dateOfBirth, :ets_pcsDate, :firstName,
:lastName, :middleInitial, :phoneNum, :phoneAreaCode, :phonePrefix,
:phoneSuffix, :rank, :email, :password, :password_confirmation,
:address_attributes
has_secure_password
has_one :address, dependent: :destroy
accepts_nested_attributes_for :address
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
before_save :create_phoneNum
validates :rank, presence: true
validates :firstName, presence: true, length: { maximum: 15 }
validates :lastName, presence: true, length: { maximum: 20 }
validates :middleInitial, presence: true, length: { maximum: 1 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email,presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :dateOfBirth, presence: true
VALID_MOS_REGEX = /\A\d{2}[a-zA-Z]\z/
validates :MOS, presence: true,
format: { with: VALID_MOS_REGEX }
validates :ets_pcsDate, presence: true
VALIDATE_AREA_PREFIX_REGEX = /\A\d{3}\z/
validates :phoneAreaCode, presence: true,
format: { with: VALIDATE_AREA_PREFIX_REGEX }
validates :phonePrefix, presence: true,
format: { with: VALIDATE_AREA_PREFIX_REGEX }
VALIDATE_SUFFIX_REGEX = /\A\d{4}\z/
validates :phoneSuffix, presence: true,
format: { with: VALIDATE_SUFFIX_REGEX }
validates :password, length: { minimum: 6 }
validates :password_confirmation, presence: true
private
def create_phoneNum
self.phoneNum = [phoneAreaCode,
phonePrefix, phoneSuffix].join(' ')
end
def create_phoneNum=(phoneNum)
split = phoneNum.split(' ', 3)
self.phoneAreaCode = split.first
self.phonePrefix = split.second
self.phoneSuffix = split.last
end
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end