Rails exit controller after rendering

Posted by codysehl on Stack Overflow See other posts from Stack Overflow or by codysehl
Published on 2012-11-11T16:57:45Z Indexed on 2012/11/11 16:59 UTC
Read the original article Hit count: 156

Filed under:
|

I have an action in my controller that I am having trouble with. This is my first rails app, so I'm not sure of the best practices surrounding rails.

I have a model called Group and a few actions that go in it's controller. I have written a test that should cause the controller to render an error in JSON because of 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

In the controller, the first if statement executes: render :json => { :message => "group_id not found" } but @group.destroy is still being executed. This seems counter-intuitive to me, I would think that the render method should exit the controller.

Why is the controller not exiting after render is called?

The purpose of this block of code is to recover gracefully when no record can be found with the passed in ID. Is this the correct way of doing something like this?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about controller