Skip to content

Commit 746a22c

Browse files
committed
Add Specify New Attributes For #find_or_create_by as a Rails til
1 parent e0adc3f commit 746a22c

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-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://tinyletter.com/jbranchaud).
1212

13-
_1046 TILs and counting..._
13+
_1047 TILs and counting..._
1414

1515
---
1616

@@ -690,6 +690,7 @@ _1046 TILs and counting..._
690690
- [Show Rails Models With Pry](rails/show-rails-models-with-pry.md)
691691
- [Show Rails Routes With Pry](rails/show-rails-routes-with-pry.md)
692692
- [Skip Validations When Creating A Record](rails/skip-validations-when-creating-a-record.md)
693+
- [Specify New Attributes For #find_or_create_by](rails/specify-new-attributes-for-find-or-create-by.md)
693694
- [Temporarily Disable strong_params](rails/temporarily-disable-strong-params.md)
694695
- [Test If An Instance Variable Was Assigned](rails/test-if-an-instance-variable-was-assigned.md)
695696
- [Truncate Almost All Tables](rails/truncate-almost-all-tables.md)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Specify New Attributes For #find_or_create_by
2+
3+
The ActiveRecord
4+
[`#find_or_create_by`](https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by)
5+
method is a handy way to get an object that represents a record. It will
6+
attempt to look up that record, usually based on a unique value or set of
7+
values. If it can find one, then that's the record you get. If nothing is
8+
found, then it will create a new record.
9+
10+
New records tend to need more data than just the unique lookup attribute. There
11+
are a couple ways these other attributes can be specified.
12+
13+
The first is by giving `#find_or_create_by` a block.
14+
15+
```ruby
16+
User.find_or_create_by(email: "some@email.com") do |new_user|
17+
new_user.admin = false
18+
new_user.password = params[:password]
19+
new_user.password_confirm = params[:password_confirm]
20+
end
21+
```
22+
23+
Another approach is to precede the `#find_or_create_by` call with a
24+
[`#create_with`](https://apidock.com/rails/ActiveRecord/QueryMethods/create_with)
25+
call.
26+
27+
28+
```ruby
29+
User.create_with(
30+
admin: false,
31+
password: params[:password],
32+
password_confirm: params[:password_confirm]
33+
).find_or_create_by(email: "some@email.com")
34+
```
35+
36+
In both cases, the extra attributes will not be applied to the `User` record in
37+
the case of a _find_; they are only used in the case of a _create_.

0 commit comments

Comments
 (0)