File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -102,6 +102,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
102
102
- [ All or Nothing Database Transactions] ( rails/all-or-nothing-database-transactions.md )
103
103
- [ Attribute Getter without the Recursion] ( rails/attribute-getter-without-the-recursion.md )
104
104
- [ Attribute Was] ( rails/attribute-was.md )
105
+ - [ Autosave False On ActiveRecord Associations] ( rails/autosave-false-on-activerecord-associations.md )
105
106
- [ Capybara Page Status Code] ( rails/capybara-page-status-code.md )
106
107
- [ Code Statistics For An Application] ( rails/code-statistics-for-an-application.md )
107
108
- [ Conditional Class Selectors in Haml] ( rails/conditional-class-selectors-in-haml.md )
Original file line number Diff line number Diff line change
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.
You can’t perform that action at this time.
0 commit comments