Skip to content

Commit 2637845

Browse files
committed
Add Autosave False On ActiveRecord Associations as a rails til.
1 parent 73f43b6 commit 2637845

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
102102
- [All or Nothing Database Transactions](rails/all-or-nothing-database-transactions.md)
103103
- [Attribute Getter without the Recursion](rails/attribute-getter-without-the-recursion.md)
104104
- [Attribute Was](rails/attribute-was.md)
105+
- [Autosave False On ActiveRecord Associations](rails/autosave-false-on-activerecord-associations.md)
105106
- [Capybara Page Status Code](rails/capybara-page-status-code.md)
106107
- [Code Statistics For An Application](rails/code-statistics-for-an-application.md)
107108
- [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md)
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Autosave False On ActiveRecord Associations
2+
3+
A relationship between two ActiveRecord models can be established with a
4+
`has_one` or `has_many` association. This relationship has some
5+
implications. By default, saving a record will also save the associated
6+
records that have since been built. Consider this example of users that have
7+
many posts (`has_many posts`).
8+
9+
```ruby
10+
> u = User.first
11+
#=> #<User ...>
12+
> u.posts
13+
#=> []
14+
> u.posts.build(title: "Some Title", content: "This is a post")
15+
#=> #<Post ...>
16+
> u.save
17+
#=> true
18+
> u.posts(reload: true)
19+
#=> [#<Post ...>]
20+
```
21+
22+
When the user is saved, the associated post that was built for that user
23+
also gets saved to the database.
24+
25+
If the association is instead defined with the `autosave` option set to
26+
false, then saving a record will not cause associated records to also be
27+
saved. The associated records will need to be saved explicitly. Consider the
28+
same example from above, but with `has_many posts, autosave: false`.
29+
30+
```ruby
31+
> u = User.first
32+
#=> #<User ...>
33+
> u.posts
34+
#=> []
35+
> u.posts.build(title: "Some Title", content: "This is a post")
36+
#=> #<Post ...>
37+
> u.save
38+
#=> true
39+
> u.posts(reload: true)
40+
#=> []
41+
```
42+
43+
The post wasn't saved with the user and it wasn't saved explicitly, so it
44+
isn't persisted to the database.

0 commit comments

Comments
 (0)