user2601288
user2601288

Reputation:

Getting Ruby error "You cannot call create unless the parent is saved"

I've read through several resources but am not having any luck finding an answer. I have the following line of code, which returns "You cannot call create unless the parent is saved":

      test.entries.create!({
        :date => date,
        :volume => 15
      })

Above this line of code, I have this:

  1.upto(5) do |i|
    test = Test.create(
      :name => "test #{i}"
    )

Both of these scripts are encapsulated inside one large loop. So the script creates test and then creates an entry on test using test.entries.create!.

However, the script is failing out because the parent has not been saved. It is my understanding that .create! does .new and .save, so the initial test should be saved. I have also tried manually putting in test.save before the error with no luck. Any thoughts?

Upvotes: 0

Views: 3082

Answers (1)

Leo Correa
Leo Correa

Reputation: 19789

what is test in your second block of code. You mean Test.create? Also, is there any validations that might be preventing the save from happening?

Try adding create! to the test.create instead so it raises an exception if there are any errors.

Upvotes: 2

Related Questions