randomguy
randomguy

Reputation: 12242

"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.

Upvotes: 31

Views: 28757

Answers (2)

nikolayp
nikolayp

Reputation: 17919

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

Upvotes: 2

MrWillihog
MrWillihog

Reputation: 2646

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"

Upvotes: 23

Related Questions