我该怎么做这个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
答案 0 :(得分:3)
您可以使用after_initialize
回调:
class User
# ..
after_initialize do
self.profile ||= self.build_profile
end
# ..
end