繁体   English   中英

更新has_one关系模型

[英]update a has_one relation model

我有两个模型

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

创建用户之后,我使用控制器的new和create动作创建了用户信息:

  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

这是我的user_information控制器的编辑和更新操作

    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

我以为我只需要查找记录并进行编辑,但是没有。 谁能帮我吗?

尝试从UserInformation http://guides.rubyonrails.org/association_basics.html#the-has_one-association中删除belongs_to :user

讨论后更新

您的链接助手应该在第一个位置使用@user两个参数。 (您可以从rake routes | grep user_information结果中看到它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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM