Why doesn't my rails controller stop execution after I returned false in a private method?
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 开发者_StackOverflow中文版=> "#{e}", :status => 400}
end
return false
end
end
def destroy
find_follow
if (@follow.destroy)
# respond_to html, js, json...
end
end
end
Your find_follow
returns nil which is fine but as you are calling destroy
method you need to write return in destroy
method only
Try
def destroy
return find_follow
You can also use before_filter
something like following
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
精彩评论