Rails exit controller after rendering

I have an action in my controller that I'm having problems with. This is my first application for rails, so I'm not sure about the best methods related to rails.

I have a model called Group and a few actions that go into it. I wrote a test that should make the controller display an error in JSON due to an invalid group id. Instead of rendering and exiting, it looks like the controller is rendering and continuing to execute.

Test

test 'should not remove group because of invalid group id' do post(:remove, {'group_id' => '3333'}) response = JSON.parse(@response.body) assert_response :success assert_equal 'Success', response['message'] end 

Controller action

 # Post remove # group_id def remove if((@group = Group.find_by_id(params[:group_id])) == nil) render :json => { :message => "group_id not found" } end @group.destroy if(!Group.exists?(@group)) render :json => { :message => "Success" } else render :json => { :errors => @group.errors.full_messages } end end 

The controller executes the first if statement: render :json => { :message => "group_id not found" } but @group.destroy is still executing. This seems intriguing to me, I think the render method should exit the controller.

Why doesn't the controller exit after calling render ?

The purpose of this block of code is to gracefully recover when an entry with an identifier is not transferred. Is this the right way to do something like this?

+7
source share
2 answers

Like @ user1022209, you can add a return to the exit action:

 render(:json => { :message => "group_id not found" }) and return 

About your code, I think I would write like this:

 def remove if(!Group.exists?(params[:group_id]) render :json => { :message => "group_id not found" } else @group = Group.find(params[:group_id] @group.destroy if @group.destroyed? render :json => { :message => "Success" } else render :json => { :errors => @group.errors.full_messages } end end end 
+15
source

Just add return; after render , to close the body of the method :)

I think render is just a call to the method you are calling, and the method will be placed on top of the stack that contains the method execution sequence. When finished, return to the remove method and continue with the rest. But you can avoid this problem by manually exiting the remove method

It is my drawing to illustrate the concept described by the words above

+7
source

All Articles