Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"return render" vs "render ... and return" in Rails

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.

like image 258
randomguy Avatar asked Jun 14 '16 11:06

randomguy


2 Answers

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"

like image 52
MrWillihog Avatar answered Nov 01 '22 02:11

MrWillihog


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

like image 29
itsnikolay Avatar answered Nov 01 '22 03:11

itsnikolay