2012-05-02 36 views
4

我该如何做这个sudo代码? 我想阻止例如“未定义的方法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 

回答

3

你可以使用after_initialize回调:

class User 
    # .. 
    after_initialize do 
    self.profile ||= self.build_profile 
    end 
    # .. 
end 
相关问题