Reputation: 73
I am new on RAILS, so don't hit me. I consider such problem:
- author
has_many :books
- book
belongs_to :author
In console I create a new author, per example:
ar = Author.new(fname: "Frank", lname: "Herbert")
ID of this record is not set before save.
Then I create some books from object ar:
ar.books.new(title: "Dune"), ar.books.new(title: "The Green Brain")
No errors. But when I list books:
ar.books.all
got an empty list.
I figured out that first I have to save ar
, and then I can add books.
Is there a way to save ar
with books, no need saving ar
without books before?
Upvotes: 2
Views: 99
Reputation: 4427
Follow below code: First create Author and then create books with author as foreign key.
ar = Author.new(fname: "Frank", lname: "Herbert")
ar.save
ar.books.create(title: "Dune")
ar.books.create(title: "The Green Brain")
OR
ar = Author.new(fname: "Frank", lname: "Herbert")
ar.books.build(title: "Dune")
ar.books.build(title: "The Green Brain")
ar.save
Upvotes: 1
Reputation: 414
Sure you can!
You need to call ar.books
to look up for books that you have added. When you call ar.books.all
ActiveRecord tries to find something in database (obviously it returns empty array). So just:
author = Author.new(fname: "Frank", lname: "Herbert")
author.books.build(title: "Dune")
author.save
It will save author & books as you expect. By the way use build
method instead of new
. In this way you show that you are going to create record soon.
Upvotes: 1