2012-12-11 32 views
0

用戶模型有一個user_profile。
我剛剛安裝了設計和它的工作正常。如何在使用Devise註冊時將值設置爲嵌套列?

我做了registrations_controller.rb,它有'create','after_update_path_for(resource) '和'edit'動作。

如果我想讓它輸入'45'到user_profile的嵌套列作爲默認值,我該如何在註冊控制器中進行編碼?

我應該做另一個叫做'save/or new?'的操作嗎? ,並寫下這個?

@ user.user_profile.language_id =「45」

+0

我想你會需要重寫,但你也可以使用回調http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html – pablomarti

+0

@ pablo89謝謝!所以你的意思是我應該在註冊控制器中做出before_create動作?但是,編碼@ user.user_profile.language_id = '45'可以嗎?我不知道如何設計保存:( – HUSTEN

+0

我沒有嘗試過(在控制器中),但我會在幾個小時內做一個測試哈哈,並且我建議你after_create(我正在考慮製作一個新對象,但可能有一個更短的方式,我會嘗試...) – pablomarti

回答

1

我做了一些測試,我建議你使用的回調,但你也可以覆蓋設計的RegistrationsController的行動。我跟着這個線程:Override devise registrations controller和控制器https://github.com/plataformatec/devise/blob/master/app/controllers/devise/registrations_controller.rb的代碼 -

(看到我用sign_in的代替sign_up我使用Rails 3.2.8的工作),這是與編輯的代碼情況:

class RegistrationsController < Devise::RegistrationsController 
    def new 
    super 
    end 

    def create 
    build_resource 

    resource.build_user_profile 
    resource.user_profile.language_id = 45 

    if resource.save 
     if resource.active_for_authentication? 
     set_flash_message :notice, :signed_up if is_navigational_format? 
     sign_in(resource_name, resource) 
     respond_with resource, :location => after_sign_up_path_for(resource) 
     else 
     set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format? 
     expire_session_data_after_sign_in! 
     respond_with resource, :location => after_inactive_sign_up_path_for(resource) 
     end 
    else 
     clean_up_passwords resource 
     respond_with resource 
    end 
    end 

    def update 
    super 
    end 
end 

而且隨着職位的回答說,我離開的路線如下:

devise_for :users, :controllers => {:registrations => "registrations"} 

我用了一個has_one的關係。

+0

謝謝!實際上我想用before_create方法作爲回調。所以我做了before_create和編碼build_resource; resource.build_user_profile; resource.user_profile.language_id = 45;內。但它沒有工作:( – HUSTEN

+0

嘗試build_user_profile; user_profile.language_id = 45; – pablomarti

+0

它仍然不會更改嵌套記錄創建時的值 – HUSTEN

相關問題