2010-12-07 50 views
1

我正在爲應用中的用戶創建通知模型。他們得到哪些電子郵件等等。Rails - 爲用戶創建通知模型

我要創建一個模型UserNotifications,每個設置都有一堆列是二進制的。

我還沒有用Rails學到的東西是,每個用戶都需要在UserNotifications模型中有記錄。那麼我該如何做到以下幾點:

  1. 當創建用戶時,在UserNotifications表中爲該用戶添加一條記錄?
  2. 處理DB中的所有現有用戶。當我遷移時,如何告訴Rails爲數據庫中的所有用戶用戶構建UserNotification記錄?

感謝您通過這個步行我。我之前在Rails中不需要創建這樣的模型。

回答

1

這是那種你在after_create做的一件事:

class User < ActiveRecord::Base 

    belongs_to :user_notification 
    after_create :create_user_notification 


    def create_user_notification 
    #additional logic probably needed per app requirements 
    user_notification.create 
    end 
end 

在遷移,你只需要遍歷現有用戶和呼叫#create_user_notification

+0

爲什麼belongs_to的,不HAS_ONE? – AnApprentice 2010-12-07 22:18:41