为什么我在私有方法中返回 false 后我的 Rails 控制器没有停止执行?
当我在以下控制器上运行 ajax POST delete 时,对于已删除的记录,rails 会引发错误“undefined method `destroy' for nil:NilClass”。但为什么当我尝试在 destory 调用之前的 find_follow 方法中呈现响应时,它仍然会这样说?执行不应该在find_follow中停止吗?
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
When I run ajax POST delete on my follows controller, for a record that has already been deleted, rails raises error "undefined method `destroy' for nil:NilClass". But why does it still say that when I tried to render the response in a find_follow method preceding the destory call? Shouldn't the execution stop inside find_follow?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
find_follow
返回 nil ,这很好,但是当您调用destroy
方法时,您只需要在destroy
方法中编写 return尝试
您也可以使用 < code>before_filter 类似以下内容
Your
find_follow
returns nil which is fine but as you are callingdestroy
method you need to write return indestroy
method onlyTry
You can also use
before_filter
something like following