2010-09-07 40 views
1

Rails 3 newbie here ....我正在建立一個應用程序,限制用戶的可查看數據到他們的公司,這是基於他們的電子郵件的域名。非常喜歡Yammer或basecamp。目前我使用的是設計一種身份驗證...Rails 3,after_create在user.rb創建一個實例關聯?

我想一個用戶表,然後一個UserInstance表...的UserInstance表看起來像:

 
ID | domain 
1 | yahoo.com 
2 | github.com 
3 | abc.com 

我想爲用戶表中的每條記錄都具有一個InstanceID,該實例ID具有UserInstance表中的ID。在註冊期間,UserInstance被找到或分配(唯一)....然後,DB中的所有記錄都將具有InstanceID。現在所有的用戶都被分配到了一個實例ID ......我希望登錄用戶在網站上看到的所有內容都只針對他們的InstanceID,因此公司的信息是孤立的。

問: 1.如何修改設計出應對支持UserInstance表,分配或創建並分配實例ID註冊

到目前爲止,我在這裏,/app/models/user.rb

class User < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
    attr_accessible :email, :password, :password_confirmation, :remember_me 

    after_create :assign_user_to_instance 

    def assign_user_to_instance 
     logger.debug "Called after the account was created" 
    end 

end 

我想看到的發生在assign_user_to_instance如下:

def assign_user_to_instance 
Step 1, extract the user's domain from the email address they just registered with 
Step 2, does this domain from s1 exist in the UserInstance Table (domain)? 
Step 2b, if not create it and grab the UserInstance.ID 
Step 2c, if it does, grab the already available UserInstanceID 
Step 3, assign the UserInstanceID to the user's record in the user table 
end 

任何幫助實現的僞代碼ABOV e將不勝感激。

謝謝!

回答

2

用戶模式:

class User < ActiveRecord::Base 
    # devise stuff 
    belongs_to :instance, :class => 'UserInstance' 
    def assign_user_to_instance 
    domain = email.split("@").last 
    user_instance = UserInstance.find_or_create_by_domain domain 
    update_attribute(:instance_id, user_instance.id) #or whatever you called this field 
    end 
end 

,你需要這樣的遷移:

> rails g migration AddUserInstanceToUser 

遷移應該是這樣的:

class AddUserInstanceToUser < ActiveRecord::Migration 
    self.up 
    add_column :users, :instance_id, :integer 
    end 
    self.down 
    remove_column :users, :instance_id 
    end 
end 
+0

這是很好!謝謝。有關如何更新我的設計用戶表的任何建議?我是否添加了添加instance_id列的遷移,或者是否存在自動執行此關係的belongs_to類型的方法? – AnApprentice 2010-09-07 16:37:45

+1

查看我的更新回答 – jigfox 2010-09-07 17:23:51

+0

謝謝,這真棒 – AnApprentice 2010-09-07 17:51:19