4

この疑似コードをどのように実行しますか? たとえば、プロファイルを持つ既存のユーザーがまだいるため、「nil クラスの未定義メソッド zip_code」を防止したいと考えています。したがって、 user.profile が呼び出されたときに、存在しない場合は作成したいと思います。

class User < ActiveRecord::Base
...
  # Associations:
  has_one :profile


  # example call current_user.profile.zip_code
  def profile
    if self.profile exists <-- use super?
      self.profile
   else
     # create association record and return it
     self.build_profile.save
     self.profile
   end
  end
...
end
4

1 に答える 1

3

コールバックを使用できafter_initializeます:

class User
  # ..
  after_initialize do
    self.profile ||= self.build_profile
  end
  # ..
end
于 2012-05-02T14:51:37.283 に答える