2012-11-06 54 views
0

我有两个型号更新HAS_ONE关系模型

class User < ActiveRecord::Base 
    has_one :user_information, :dependent => :destroy 
    attr_accessible :email, :name 
end 

class UserInformation < ActiveRecord::Base 
    belongs_to :user 
    attr_accessible :address, :business, :phone, :user_id 
end 

创建的用户后,我创建使用新的和我的控制器的创建操作的用户信息:

def new 
     @user = User.find(params[:id]) 
     @user_information = @user.build_user_information 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @user_information } 
    end 
    end 



def create 
    @user_information = UserInformation.new(params[:user_information]) 

    respond_to do |format| 
     if @user_information.save 
     format.html { redirect_to @user_information, notice: 'User information was successfully created.' } 
     format.json { render json: @user_information, status: :created, location: @user_information } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @user_information.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

一切工作正常,但当我尝试更新记录我得到这个错误:

RuntimeError in User_informations#edit 

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id 

下面是编辑和

def edit 
     @user_information = UserInformation.find(params[:id]) 
     end 

    def update 
    @user_information = UserInformation.find(params[:id]) 

    respond_to do |format| 
     if @user_information.update_attributes(params[:user_information]) 
     format.html { redirect_to @user_information, notice: 'User information was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: "edit" } 
     format.json { render json: @user_information.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

我想我只需要找到记录和编辑,但没有我的user_information控制器的更新操作。任何人都可以帮助我吗?

+0

拼写User_informations#edit'是让我信服。你能显示控制器类名和文件名吗? – ck3g

+0

确定控制器名称是UserInformationsController,文件名是user_informations_controller和编辑记录的路径是http://本地主机:3000 /用户/ 1/user_informations/1 /编辑 – Jean

+0

所以,你的链接帮助应该是'users_user_information(USER_ID, user_info_id)'。助手的名字可以不同,但​​要注意两个参数。 – ck3g

回答

0

尝试讨论后从UserInformation http://guides.rubyonrails.org/association_basics.html#the-has_one-association

更新删除belongs_to :user

您的链接助手应在第一个位置有两个参数与@user。 (你可以看到它从rake routes | grep user_information结果)

<%= link_to 'Edit', edit_user_information_path(@user, @user_information) %> 

其次所有的在你的控制器

params[:id] # => @user.id 
params[:user_information_id] # => @user_information.id 

所以,你应该改变的`find

@user_information = UserInformation.find(params[:user_information_id]) 
+0

我不能那样做。我需要这种关联 – Jean

+0

'HAS_ONE:user_information'就够了。请参阅上面的链接。 – ck3g

+0

谢谢ck3g,我尝试了你的建议,但我仍然有同样的错误,当我尝试更新记录 – Jean