2011-09-14 32 views
0

我有一個用一個簡單的模型,用戶一一對應關係和型材型號:使用.build方法通過1​​to1協會創建

模型/用戶

class User < ActiveRecord::Base 
    authenticates_with_sorcery! 

    attr_accessible :email, :password, :password_confirmation 

    has_one :profile, :dependent => :destroy 

    validates_presence_of :password, :on => :create 
    validates :password, :confirmation => true, 
         :length  => { :within => 6..100 } 

    email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 
    validates :email, :presence  => true, 
        :format   => { :with => email_regex }, 
        :uniqueness  => {:case_sensitive => false}, 
        :length   => { :within => 3..50 } 
end 

型號/配置文件

  # == Schema Information 
    # 
    # Table name: profiles 
    # 
    # id   :integer   not null, primary key 
    # weight  :decimal(,) 
    # created_at :datetime 
    # updated_at :datetime 
    # 

    class Profile < ActiveRecord::Base 
     attr_accessible :weight 

     belongs_to :user 

    end 

我這樣做是因爲我希望用戶能夠隨着時間的推移跟蹤體重以及在配置文件中存儲其他更多靜態數據(如高度)。

但是,我的新建和創建方法似乎沒有正常工作。我在提交新動作我得到這個錯誤:

undefined method `build' for nil:NilClass 

profile_controller

class ProfilesController < ApplicationController 

    def new 
    @profile = Profile.new if current_user 
    end 

    def create 
    @profile = current_user.profile.build(params[:profile]) 
    if @profile.save 
     flash[:success] = "Profile Saved" 
     redirect_to root_path 
    else 
     render 'pages/home' 
    end 
    end 

    def destory 
    end 

end 

和新

<%= form_for @profile do |f| %> 
    <div class="field"> 
     <%= f.text_field :weight %> 
    </div> 
    <div class="actions"> 
     <%= f.submit "Submit" %> 
    </div> 
<% end %> 

預先感謝您也許能幫忙縱斷面圖給。 Noob在這裏!

回答

2

has_one關聯的構建語法與has_many關聯不同。如下 更改代碼:

@profile = current_user.build_profile(params[:profile]) 

參考:SO Answer

+0

唉唉,天才!謝謝! – Rapture