ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.string :title
end
create_table :comments, force: true do |t|
t.integer :post_id
t.string :body
end
end
class Post < ActiveRecord::Base
has_many :comments, inverse_of: :post
accepts_nested_attributes_for :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
> post = Post.build(title: 'Intro Post 1', comments_attributes: [{ body: "Comment 1" }, { body: "Comment 2" }] )
> post.comments.count
=> 0
> post.comments.size
=> 2
> post.comments
=> []
> post.comments.class
=> Post::ActiveRecord_Associations_CollectionProxy
> post.comments.to_a
=> [#<Comment:0x00007fd923e30b30 id: nil, post_id: nil, body: "Comment 1">,
#<Comment:0x00007fd924df5408 id: nil, post_id: nil, body: "Comment 2">]
> post.comments
=> [#<Comment:0x00007fd923e30b30 id: nil, post_id: nil, body: "Comment 1">,
#<Comment:0x00007fd924df5408 id: nil, post_id: nil, body: "Comment 2">]