I have two models with a one-to-one association.
class User < ActiveRecord::Base
has_one :setting
end
class Setting < ActiveRecord::Base
belongs_to :user
end
Each model has plenty of fields and user is used quite extensively by a non rails external server, which is why I have separated the tables.
I am trying to use the build_association but all I get is undefined method `build_setting’ for nil:NilClass. I want to do this because I want a single form with fields from both models to setup a new user.
In my user controllers new method I try this:
def new
@user = User.new
@setting = @user.setting.build_setting
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @user }
end
end
Which throws:
NoMethodError in UsersController#new
undefined method `build_setting' for nil:NilClass
Why? According to the api docs this is the way to do it.
Doing this seems to work, but its not the right way (or is it?):
def new
@user = User.new
@setting = Setting.new
@user.setting=@setting
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @user }
end
end
In your users model add
and then use