0

私は2つのモデルを持っています

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

これが私の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

レコードを見つけて編集するだけでいいと思いましたが、違います。誰か助けてくれませんか?

4

1 に答える 1

0

http://guides.rubyonrails.org/association_basics.html#the-has_one-associationから削除してみてbelongs_to :userくださいUserInformation

議論後に更新

リンクヘルパーは@user、最初の位置で2つの引数を取る必要があります。(の結果からわかります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])
于 2012-11-06T19:45:00.707 に答える