2014-09-11 1 views
0

를 예상하는대로 편집이 작동하지 않습니다 내가 가지고 레일 컨트롤러에서 다음 두 가지 방법 :렌더링 : 나는

def edit 
    @blog = Blog.find_by!(id: params[:id]) 
    end 

    def update 
    blog = Blog.find_by!(id: params[:id]) 
    user = User.find_by!(id: params[:user_id]) 

    blog.update_attributes(blog_update_params) 
    if blog.save 
     flash[:success] = 'Updated Blog' 
     redirect_to user_blog_path(user.id, blog.id) 
    else 
     render :edit 
    end 
    end 

이 실패이 업데이트를 가정 할 수 있습니다, 확인 그래서 당신이 내 마음에, 의미 render :edit을해야 블로그의 ID를 편집 작업에 전달하고 양식을 다시 렌더링해야합니다. 그러면 다음과 같은 오류가 표시됩니다.

<div class="container-sm"> 
    <%= form_for @blog, :url => user_blog_path(current_user.id, @blog.id), :html => {:class => 'form-horizontal'} do |f| %> 
    <div class="form-group"> 
     <div class="col-sm-offset-2 col-sm-10"> 
     <h1>Edit <%= @blog.title %></h1> 
     <p class="text-muted">Want to change the name? Never a simpler place!</p> 
     </div> 
    </div> 

    <div class="form-group"> 
     <div class="col-sm-offset-2 col-sm-6"> 
     <%= render :partial => 'form_errors', :object => @blog %> 
     </div> 
    </div> 
    <%= render :partial => 'blog_form', :locals => {:f => f} %> 
    <div class="form-group"> 
     <div class="col-sm-offset-2 col-sm-10"> 
     <%= f.submit "Update", :class => 'btn btn-primary' %> 
     </div> 
    </div> 
    <% end %> 
</div> 

위의 편집 양식이 기본입니다. 아주 간단합니다. 모든 사람이 행복하다. 우리는 여전히 가정에서 사는 경우 업데이트는이 양식을 다시 렌더링해야 실패하지만, 문제는이다 : 전무에 대한 undefined method ID '내가 잘못 여기서 뭐하는 거지

<%= form_for @blog, :url => user_blog_path(current_user.id, @blog.id), :html => {:class => 'form-horizontal'} do |f| %> 

:에서 발생 NilClass` ? 모든 자습서, 양식 게시 또는 스택 질문에서는 양식을 다시 렌더링하여 오류를 표시하는 방법을 설명합니다.

binding.pryrender :edit 위로 놓은 다음 복사하여 붙여 넣으면 물리적으로 편집 작업이 렌더링되도록하려면 @blog이 비어 있습니다. current_user는 현재 사용자를 포함하며,이 경우에는 @blog이 nil입니다.

그래서 내가 뭘 잘못하고 있니?

답변

0

컨트롤러 동작에 @blog을 설정하지 않았습니다. blog을 설정하고 있습니다.

편집 작업과 마찬가지로 렌더링을 위해보기로 전달되는 인스턴스 변수 여야합니다.

관련 없음, 그러나 Blog.find_by!(id: params[:id])Blog.find(params[:id])으로 단순화 할 수 있습니다.

관련 문제