2011-09-14 70 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