2011-12-15 68 views
0

我使用Devise進行身份驗證,添加了兩個自定義字段= :organization_id:username。我還爲本組織創建了一個腳手架,該組織僅由Name組成。用戶註冊時自動創建「組織」?

當前用戶註冊時,他們可以輸入組織ID(整數)和用戶名(字符串)。

用戶belong_to組織和組織has_many用戶。

這裏是我的模型的樣子(我離開一切,除了應用程序/視圖/設計/註冊裏的文件添加的organization_ID和用戶名不變):

#user.rb

class User < ActiveRecord::Base 
    belongs_to :organization 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me, :organization_id, :username 

end 

#organization.rb

class Organization < ActiveRecord::Base 
    has_many :users 
end 

我希望在用戶註冊時自動創建組織,而無需用戶指定organization_id。

而且,理想的@organization.name將是完全一樣:username

我怎麼會去這樣做呢?

我在nested model forms上看到了Railscast,但他在調查表中創建了一個問題,問題屬於一項調查。我需要周圍的人它的其他方式(創建用戶表單,用戶屬於一個調查內部的組織。)

任何幫助和建議將不勝感激..

回答

1
class User < ActiveRecord::Base 
    before_create :create_organization 

    private 
    def create_organization 
    self.organization = Organization.create :name => self.username 
    end 
end 

create_organization方法將在創建用戶的sql查詢之前執行。它會創建一個新的組織並將其分配給用戶。

+0

哇,真棒,工作!你不知道我是多麼激動地看到這一點。有什麼辦法可以這樣做:username = @ organization.name? – cdotfeli 2011-12-15 14:27:12