Skip to content

Commit e7457a9

Browse files
committed
Add Why Redirect And Return In Controllers as a Rails TIL
1 parent 117856c commit e7457a9

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1260 TILs and counting..._
13+
_1261 TILs and counting..._
1414

1515
---
1616

@@ -857,6 +857,7 @@ _1260 TILs and counting..._
857857
- [Use IRB And Ruby Flags With Rails Console](rails/use-irb-and-ruby-flags-with-rails-console.md)
858858
- [Verify And Read A Signed Cookie Value](rails/verify-and-read-a-signed-cookie-value.md)
859859
- [Where Am I In The Partial Iteration?](rails/where-am-i-in-the-partial-iteration.md)
860+
- [Why Redirect And Return In Controllers](rails/why-redirect-and-return-in-controllers.md)
860861
- [Wipe Out All Precompiled Assets](rails/wipe-out-all-precompiled-assets.md)
861862
- [Write Reversible Migration To Set Default](rails/write-reversible-migration-to-set-default.md)
862863
- [Write Safer Where Clauses With Placeholders](rails/write-safer-where-clauses-with-placeholders.md)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Why Redirect And Return In Controllers
2+
3+
A fairly common idiom in Rails controller actions is a `redirect_to` followed
4+
by an `and return`.
5+
6+
```ruby
7+
def show
8+
redirect_to sign_in_path and return if current_user.blank?
9+
10+
book = Book.find(params[:id])
11+
12+
render book
13+
end
14+
```
15+
16+
Because a `render` comes later in the controller action, we need to _early
17+
return_ after the redirect to avoid multiple render/redirect warnings.
18+
19+
It is important to use `and` here instead of `&&` because of logical operator
20+
precedence.
21+
22+
If we used `&&` instead:
23+
24+
```ruby
25+
redirect_to sign_in_path && return if current_user.blank?
26+
```
27+
28+
The `redirect_to` would get `nil` (the result of `sign_in_path && nil`). If we
29+
did want to use `&&`, we'd need to be diligent with method call parentheses.
30+
31+
```ruby
32+
redirect_to(sign_in_path) && return if current_user.blank?
33+
```
34+
35+
In this case, `redirect_to` would actually get called with a path string and
36+
the `return` would be called after that.
37+
38+
[source](https://stackoverflow.com/a/37211314/535590)

0 commit comments

Comments
 (0)