29

Is there any functional difference in writing return render 'edit' and render 'edit' and return? Are both syntaxes safe to use?

The return render syntax is slightly more concise, but the render and return is advocated officially here Avoiding Double Render Errors.

return render would return whatever value the render method return and render and return would return a nil from the controller method.

randomguy
  • 12,042
  • 16
  • 71
  • 101
  • 4
    Another tricky thing is to use `render and return`, don't do `render && return`, although your Rubocop may not favour it. – LYu Feb 24 '17 at 02:24
  • 2
    Rubocop does indeed flag it and suggests using `&&`. Rubocop isn't always right. – Steven Hirlston Mar 13 '18 at 18:14
  • 6
    I personally think `return render` is much clearer, especially if the call is long, and the `and` far right. Visually, `return render` is crystal clear. – akim Feb 13 '19 at 12:46
  • 1
    See [this question](https://stackoverflow.com/questions/39629976/ruby-return-vs-and-return) for why you should be careful about using `render "foo" && return`. Note also that you can get around the linting issue by adding parentheses with your render method like so: `render("foo") && return` – Roger Miller Jul 30 '20 at 23:38

2 Answers2

22

You answered your question at the end:

return render would return whatever value the render method return and render and return would return a nil from the controller method

The important thing is that you are returning - this prevents any other code in the controller action from running - hence protecting you from double render errors. I don't believe anything is actually listening for the return value of the controller actions.

If I had to guess why the preferred method is and return I would say that it reads like prose, which is the ruby way. That is to say, it sounds like a sentence "Render categories and return" rather than "return render categories"

MrWillihog
  • 2,586
  • 19
  • 17
2

All methods in Ruby return a result related on the last method's line. If you want to return a result without waiting whole method, you can return value with keyword return

Example:

def hello1
  'I m first' # executes but is never returned
  'I m second' # result
end

def hello2
  return 'I m first' # result
  'I m second' # this line will be never executeed
end

puts hello1
# => 'I m second'
puts hello2
# => 'I'm first'

And the method render acts the same way

But render method is written like a procedure (it has result, but the result is a true), thus you can just return after render call

richessler
  • 84
  • 6
itsnikolay
  • 17,415
  • 4
  • 65
  • 64