2011-09-22 54 views
0

当我在我的跟随控制器上运行ajax POST delete时,对于已经被删除的记录,rails会在“nil:NilClass”引发错误“未定义方法destroy”。但为什么它仍然会说,当我尝试在destory调用之前的find_follow方法中呈现响应时?执行不应该停止在find_follow里面吗?为什么在我私有方法返回false后,我的rails控制器不会停止执行?

class FollowsController < ApplicationController 


def find_follow 
    begin 
    @follow = current_artist.follows.find(params[:id]) 
    raise "Record Not Found" if @follow.nil? 
    rescue => e 
     respond_to do |format| 
     format.html { redirect_to(artist_follows_path(current_artist),:notice => "#{e}") } 
     format.js { render :text => "#{e}", :status => :not_found} 
     format.json {render :json => "#{e}", :status => 400} 
     end 
     return false 
    end 
    end 


    def destroy 
    find_follow 
    if (@follow.destroy) 
     # respond_to html, js, json... 

    end 

    end 
end 

回答

1

find_follow返回nil这是好的,但因为你调用destroy方法,你需要写在destroy方法只返回

尝试

def destroy 
    return find_follow 

您还可以使用before_filter类似以下

class FollowsController < ApplicationController 
before_filter :find_follow, :only=>[:destroy] 

def find_follow 
    @follow = current_artist.follows.find_by_id(params[:id]) 
    if @follow.nil? 
     redirect_to(artist_follows_path(current_artist),:notice => "#{e}") 
    else 
     return true 
    end 
    end 


    def destroy 
    if (@follow.destroy) 
     # respond_to html, js, json... 

    end 

    end 
end 
+0

确实这意味着无法停止从私有方法执行控制器?还是只为摧毁方法?我试图通过让find_follow方法在无法找到记录时停止执行来干起我的控制器。 – Homan

+0

检查我编辑的答案,我使用'find_by_id',因为它没有抛出记录未找到 – Salil

+0

使用之前的过滤器工作正如你所建议的。但是,我不确定这是为什么这是有效的?我认为从destroy方法调用单独的方法与使用before_filter相同,但显然不是。 – Homan

相关问题