2011-09-14 3 views
0

I 간단한 사용자 모델 한 관계로 하나와 정보 모델 가지고1 대 1 연결을 만드는 방법 .build 사용

모델/사용자

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 %> 

감사에 대한 프로필보기 : 나는에 나는이 오류가 새로운 조치 제출 주기. 여기 멍청한 녀석!

답변

2

has_one 연결에 대한 빌드 구문이 has_many 연결과 다릅니다. 다음과 같이 코드를 변경 :

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

참조 : SO Answer

+0

아, 천재! 감사! – Rapture