Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning from rails controller

Here's a beginner rails question...

After I do:

format.xml { head: ok}

How do I return from the controller endpoint without showing the view? If I drop off the end of the function at this point, I get what I expect, but if I call 'return', I end up in the view (or in my case in a missing view template). I can code up lots of if/else etc., but it would be nice to early out from the function without ending up in a view template.

I've searched around and can't figure out what the obvious answer is to this; it must be straightforward...

like image 969
cmaughan Avatar asked Jun 09 '09 08:06

cmaughan


People also ask

How do I redirect back in Rails?

In Rails 4. x, for going back to previous page we use redirect_to :back. However sometimes we get ActionController::RedirectBackError exception when HTTP_REFERER is not present. This works well when HTTP_REFERER is present and it redirects to previous page.

Does redirect_to return?

redirect_to is not return Keep in mind that redirect_to does not cause the action to stop executing. It is not like calling return in a Ruby method.

What is controller callback in Rails?

A callback allows you to run some code (usually a method) automatically when another piece of code runs. In Rails, you'll commonly see callbacks that run before, after or even around other bits of code. Callback functions are minimizing the length of codes in controllers.

What does Before_action do in Rails?

When writing controllers in Ruby on rails, using before_action (used to be called before_filter in earlier versions) is your bread-and-butter for structuring your business logic in a useful way. It's what you want to use to "prepare" the data necessary before the action executes.


1 Answers

You can use "render :nothing => true, :status => :ok" to return without rendering anything, once you have send a render :nothing => true you need to return from the controller, something like this might work. You can swap the head() method call for a render => :nothing followed by a return, the head() method is documented here:

  • api.rubyonrails.org/classes/ActionController/Base.html#M000635

Here's the code that should do it for you...

  • gist.github.com/126367

Ping me if that doesn't properly answer your question, documentation for the render call with some helpful user comments can be found here:

  • apidock.com/rails/ActionController/Base/render

(sorry I couldn't hyperlink the links for you, as a new user stackoverflow won't allow me to post more than one!)

like image 63
Lee Hambley Avatar answered Sep 25 '22 21:09

Lee Hambley