2011-07-19 20 views
0

プロファイル用の関連フォームを作成しようとしていますが、送信ボタンを押したときに何らかの理由でNoMethodErrorが表示されています。私は、次のよチュートリアル...と同じチュートリアルは古くなっていない限り...

def create
@user = User.find(params[:user_id])
@profile = @user.profiles.create(params[:profile])
redirect_to user_path(@user)
end

NoMethodError in ProfilesController#create

誰かが私がnonameエラーを取得している理由を知っていますか?コントローラに属し 形式は以下の通りです: https://github.com/imjp/SuperModel/blob/master/app/views/users/show.html.erb


EDIT 1:は固定します!次のコードは、しかし(プロファイル#ショーである)http://localhost:3000/users/2でプロファイルデータが表示されていない。ここで<%= @user.profile.first_name %>

は私の現在のプロファイル#はEDIT 2
def show
@user = User.find(params[:user_id])
@profile = @user.profile.find(params[:id])
end

を示します:私のgithubリポジトリをhttps://github.com/imjp/SuperModelに更新しました

+0

create_profileを試すことができます! (!bang版で)例外が発生していないかどうかを確認します。プロファイルモデルで検証エラーまたはattr_accessible/protectedが設定されている可能性があります。 – kain

+0

Naw、動作しません。上記の私のショーアクションをペーストしました。何が原因でこのエラーが発生する可能性がありますか? '未定義メソッド 'first_name' for nil:NilClass' – imjp

+0

@profile = @ user.profile – kain

答えて

1

なぜ@ user.profilesですか? @ user.profile(単数)を試してください

+0

これも試しましたが、このエラーが発生します: 'undefined method 'create for nil:NilClass' – imjp

+0

おそらくユーザhas_oneプロファイルはコンストラクタが異なるので、try @ user.create_profile(params [:profile]) – kain

+0

ありがとう!私はもうエラーは出ません:)私は格納された変数にアクセスすることはできません。編集したバージョンを確認してください – imjp

1

そのIDを持つユーザーが見つかりませんでしたので、undefined method 'first_name' for nil:NilClassが届きました。あなたはおそらく間違ったparamか何かを送るでしょう。あなたのショーアクションのURLはどのように見えますか?

編集:あなたは、これは、アプリで自分のフォームを変更する変更した後、あなたがこの

def create 
@user = User.new(params[:user]) 
@user.build_profile 

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

にusers_controller.rbでメソッドを作成

変更/ビュー/ユーザー/ show.html.erbこの

<h3>Add Profile</h3> 
<%= form_for([@user, @user.profile]) do |f| %> 
<div class="field"> 
    <%= f.label :first_name %><br /> 
    <%= f.text_field :first_name %> 
</div> 
<div class="field"> 
    <%= f.label :last_name %><br /> 
    <%= f.text_field :last_name %> 
</div> 
<div class="field"> 
    <%= f.label :picture %><br /> 
    <%= f.text_field :picture %> 
</div> 
<div class="field"> 
    <%= f.radio_button(:sex, "male") %> 
    <%= f.label(:sex, "Male") %> 
    <%= f.radio_button(:sex, "female") %> 
    <%= f.label(:sex, "Female") %> 
</div> 
<div class="actions"> 
    <%= f.submit %> 
</div> 
<% end %> 

から、それが動作します。あなたのユーザープロフィールの関連付けは構築されませんでした。

+0

貼り付けました。助けてくれてありがとう。 – imjp

+0

問題はありません、私は自分の投稿を編集しました。 – shime

+0

まだ動作しません:(ユーザーhas_one:プロフィールプロフィールbelongs_to:ユーザー – imjp

関連する問題