开发者

build_association working?

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


You need to use:

@setting = @user.build_setting

This is after an edit, so if you like this answer, accept Mahesh's below.


In your users model add

class User < ActiveRecord::Base
  has_one  :setting
  validates_associated :setting
end

and then use

@setting = @user.build_setting
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜