1

我有客户模型和细节模型。详细模型必须与客户一起创建。

class Client < AdminUser

  has_one :detail, class_name: 'ClientDetail', autosave: true
  delegate  :phone,:phone=, :name, :name=, to: :detail, prefix: true
  after_initialize :prebuild_details

  attr_accessible :detail_phone, :detail_name

  validates :detail_phone, :detail_name, presence: true

  private
  def prebuild_details
    logger.info 'WE GONNA CALL SOME BUILD!!! 'if detail.nil?
    build_detail if detail.nil?
  end

end

class ClientDetail < ActiveRecord::Base
  belongs_to :client
  attr_accessible :phone, :name
end

而且 Detail 属性是空的!:(

s =  Client.new(email: Faker::Internet.email, password: password,password_confirmation: password, detail_name: Faker::Lorem.word,detail_phone: Faker::PhoneNumber.phone_number )
WE GONNA CALL SOME BUILD!!! 
   (0.1ms)  SAVEPOINT active_record_1
   (0.1ms)  RELEASE SAVEPOINT active_record_1
=> #<Client id: nil, email: ....>
irb(main):006:0> s.valid?
=> false
irb(main):007:0> s.detail_phone
=> nil
irb(main):008:0> s.detail_name
=> nil

有什么问题?

4

0 回答 0