2012-05-02 40 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 
相關問題