如果关联记录在访问时不存在,如何创建关联记录?

时间:2012-05-02 14:26:04

标签: ruby-on-rails model associations

我该怎么做这个sudo代码? 我想阻止例如“未定义的方法zip_code for nil class”,因为我已经拥有了我们的配置文件的用户。因此,当调用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

1 个答案:

答案 0 :(得分:3)

您可以使用after_initialize回调:

class User
  # ..
  after_initialize do
    self.profile ||= self.build_profile
  end
  # ..
end