2011-09-30 87 views
3

我有一個Rails 3.1的應用程序與色器件:創建註冊時用戶配置文件添加會員表格字段,制定註冊#新形式

  • 用戶HAS_ONE輪廓
  • 檔案belongs_to的用戶
  • 駁回了色器件registration_controller
  • 海關注冊視圖中的所有工作正常,登記工作正常

現在我可以立提交表單 時

  • 在註冊頁面上我想從配置文件中添加字段,如名字,姓氏
  • 沒有用戶然而,這是要創建:柯添加此
  • 我需要用這個名字創建的配置文件,最後

我該怎麼做?我嘗試了幾個想法,也從堆棧溢出,但似乎無法得到它的工作。我嘗試過使用嵌套屬性至極不正常的方式做到這一點會在用戶註冊至極插入第一個名字和姓氏

我註冊#新視圖的那一刻創建一個數據庫中的資料記錄:

= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| 

    = devise_error_messages! 

    = f.input :username,     :label => 'Username' 
    = f.input :email,      :label => 'Email' 
    = f.input :password,     :label => 'Password' 
    = f.input :password_confirmation,  :label => 'Password confirm' 

    // start fields for profile 
    = f.fields_for :profile do |f| 
     = f.label :bod_day 
     = f.text_field :bod_day 
    // end fields for profile 


    = f.button :submit, t(:submit, :scope => :register) 

在我的用戶模型中,我有這樣的:

accepts_nested_attributes_for :profile 

回答

5

我認爲問題是,當表單呈現該用戶不存在配置文件,一個簡單的方法來避開這可能是建立在內存中呈現的字段像這樣前:

= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| 

    = devise_error_messages! 

    = f.input :username,     :label => 'Username' 
    = f.input :email,      :label => 'Email' 
    = f.input :password,     :label => 'Password' 
    = f.input :password_confirmation,  :label => 'Password confirm' 

    // make a new profile in memory 
    = resource.build_profile 

    // start fields for profile 
    = f.fields_for :profile do |f| 
     = f.label :bod_day 
     = f.text_field :bod_day 
    // end fields for profile 


    = f.button :submit, t(:submit, :scope => :register) 
+0

謝謝我完全錯過了作爲相對紅寶石新手的這個,有時候事情似乎並不複雜,然後他們看起來。謝謝!這解決了我的問題與下面的增加 – Rubytastic

+0

Thx解決它(忘了回覆我的藉口) – Rubytastic

+0

它是有點「髒」初始化視圖中的模型。我嘗試覆蓋註冊控制器,但沒有「掛鉤」來覆蓋資源初始化而不重複代碼。有任何想法嗎? – nakhli

2

除了內斯比特的解決方案,將它添加到你的模型

attr_accessible ..., :profile_attributes 
+0

總是必要的是,謝謝你回答它現在終於正常工作 – Rubytastic

+0

你可以指定哪個模型應該去attr_accesible? –