2010-11-29 78 views
3

我想重寫Devise的RegistrationsContollers'創建操作,這樣當用戶註冊時,我可以將UserProfile模型與該用戶相關聯。如何在用戶註冊時向用戶添加UserProfile? (Devise,Rails 3)

因此,以下的設計自述文件中的指導方針,我重寫動作:

#File app/controllers/registrations_controller.rb:  
class Users::RegistrationsController < Devise::RegistrationsController 
    def create 
    # some code here.. 
    self.user_profiles.build #Error (no method `user_profiles`) 
    current_user.user_profiles.build #Error (current_user is nil) 
    some other way??? 
    end 
end 

#File routes.rb: 
devise_for :users, :controllers => { :registrations => 'users/registrations' } 

設計是建立在users表中的記錄,但我怎麼關聯與記錄中的UserProfile

我試過谷歌搜索,但我根本無法得到這個工作!任何幫助深表感謝。

(我現在用的設計1.1.5 on Rails的3.0.3)

解決:

,然後將溶液爲他人的利益:

#File app/controllers/registrations_controller.rb:  
class Users::RegistrationsController < Devise::RegistrationsController 
    def create 
    super 
    @user.build_user_profile 
    @user.user_profile.some_data = 'abcd' 
    @user.save! 
    end 
end 

回答

3

self指在這種情況下控制器不是模型。

此外,用戶模型是否有許多UserProfiles?否則,如果他們不這樣做(即它們只能有一個),那麼你應該使用@user.build_user_profile,不@user.user_profiles.build

我也建議使用回調在模型級別,而不是控制器級這樣做,如before_createafter_create,即:

class User < AR 
    has_one :user_profile 

    after_create :build_profile 

    def build_profile 
     self.build_user_profile 
     ... 
    end 
end 
+0

謝謝!該工程(@ user.build_user_profile)。另外,我需要在控制器中創建配置文件(不在模型中),因爲在註冊時(如地址)需要來自用戶的一些輸入。 – Zabba 2010-11-29 19:24:39

相關問題