You cannot call create unless the parent is saved error when seeding in rails

Cristi picture Cristi · Mar 6, 2015 · Viewed 18.2k times · Source

I'm trying to populate my SQLite3 database with a simple seed file that is supposed to create a bunch o movies entries in the Film table and then create some comments to this movies that are stored in Comments table.

formats = %w(Beta VHS IMAX HD SuperHD 4K DVD BlueRay)
30.times do
  film = Film.create(title: "#{Company.bs}",
                 director: "#{Name.name}",
                 description: Lorem.paragraphs.join("<br/>").html_safe,
                 year: rand(1940..2015),
                 length: rand(20..240),
                 format: formats[rand(formats.length)]
  )
  film.save
  (rand(0..10)).times do
    film.comments.create( author: "#{Name.name}",
                          title: "#{Company.bs}",
                          content: Lorem.sentences(3).join("<br/>").html_safe,
                          rating: rand(1..5)
      )
  end
end

Once i execute rake db:seed I inevitably get the error

ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved

and no records are added to either Films or Comments

My film.rb file is

class Film < ActiveRecord::Base
  has_many :comments

  validates_presence_of :title, :director
  validates_length_of :format, maximum: 5, minimum:3
  validates_numericality_of :year, :length, greater_than:  0
  validates_uniqueness_of :title
  paginates_per 4
end

The length limit on 'format' raises the error when creating a Film with formats selected from the 'format' list

Answer

messanjah picture messanjah · Mar 7, 2015

ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved

This occurs when you try to save a child association (Comment) but the parent (Film) isn't saved yet.

It seems that film is not saved. Looking at the code, it appears that film = Film.create(...) is failing validations and thus film.comments.create(..) cannot proceed. Without knowing more about which validation is failing, that's all I can say.

I would recommend using create!(...) everywhere in seeds.rb. The bang version will raise an exception if the record isn't valid and help prevent silent failures.