Skip to content

Commit 05bfcf0

Browse files
committed
Introduce ActiveModel::NestedAttributes
Largely inspired by the Active Record implementation, this commit introduces support for assigning instances of objects to classes that `include ActiveModel::Model`. It aims to handle assignment of `_attributes`-suffixed values in an ActionView- and ActionPack-compliant way: ```ruby Author = Struct.new(:name) Category = Struct.new(:name) class Article include ActiveModel::Model include ActiveModel::NestedAttributes attr_accessor :author attr_accessor :tags accepts_nested_attributes_for :author accepts_nested_attributes_for :tags, class_name: Category end article = Article.new( author_attributes: { name: "Pseudo Nym" }, tags_attributes: { 0 => { name: "actionview" }, 1 => { name: "actionpack" }, } ) article.author.name # => "Pseudo Nym" article.tags.pluck(:name) # => ["actionview", "actionpack"] ```
1 parent 488a7ce commit 05bfcf0

File tree

5 files changed

+1162
-0
lines changed

5 files changed

+1162
-0
lines changed

activemodel/CHANGELOG.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,35 @@
1+
* Introduce `ActiveModel::NestedAttributes`
2+
3+
Handle assignment of `_attributes`-suffixed values in an ActionView- and
4+
ActionPack-compliant way:
5+
6+
```ruby
7+
class Article
8+
include ActiveModel::Model
9+
include ActiveModel::NestedAttributes
10+
11+
attr_accessor :author
12+
attr_accessor :tags
13+
14+
accepts_nested_attributes_for :author, class_name: Author
15+
accepts_nested_attributes_for :tags, class_name: Tag
16+
end
17+
18+
19+
article = Article.new(
20+
author_attributes: { name: "Pseudo Nym" },
21+
tags_attributes: {
22+
0 => { name: "actionview" },
23+
1 => { name: "actionpack" },
24+
}
25+
)
26+
27+
article.author.name # => "Pseudo Nym"
28+
article.tags.pluck(:name) # => ["actionview", "actionpack"]
29+
```
30+
31+
*Sean Doyle*
32+
133
* Port the `BeforeTypeCast` module to Active Model. Classes that include
234
`ActiveModel::Attributes` will now automatically define methods such as
335
`*_before_type_cast`, `*_for_database`, etc. These methods behave the same

activemodel/lib/active_model.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ module ActiveModel
5050
autoload :Model
5151
autoload :Name, "active_model/naming"
5252
autoload :Naming
53+
autoload :NestedAttributes
5354
autoload :SecurePassword
5455
autoload :Serialization
5556
autoload :Translation

0 commit comments

Comments
 (0)