Using .build method to create through 1to1 association
I have a one to one relationship with a simple users model and a profiles model:
models/user
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+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => {:case_sensitive => false},
:length => { :within => 3..50 }
end
models/profile
# == 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
I am doing it this way because I would like users to be able to track weight over time as well as store other more static data like height in profiles.
However, my new and create methods don't seem to be working correctly. I on submit of the new action I get this error:
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
and profile view for new
<%= form_for @profile do |f| %>
<div class="field">
<%= f.text_field :weight %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
Thanks in advance for any help you might be able to give. Noob here!
The build syntax for has_one
association is different from has_many
association.
Change your code as follows:
@profile = current_user.build_profile(params[:profile])
Reference: SO Answer
精彩评论