Create seed file from data already in the database

后端 未结 4 499
再見小時候
再見小時候 2020-12-07 20:06

I\'m using Rails 3.0.3 and have data for my \"categories\" table already in the database, but want to create a seed file from it. Is there any rake task that will generate t

4条回答
  •  遥遥无期
    2020-12-07 20:43

    Old question, I have a new one based on @Brian's answer.

    If you want to keep the entire row as is:

    seedfile = File.open('db/seeds.rb', 'a')
    
    c = Category.all
    
    c.each do |cat|
      seedfile.write "Category.create(#{cat.attributes})\n"
    end
    
    seedfile.close
    

    If you want to only write some attributes, change the write line to the following:

    seedfile.write "Category.create(#{cat.attributes.slice('attr1', 'attr2', ...})\n"
    

    Or, if you wish all the attributes except some, for example timestamps:

    seedfile.write "Category.create(#{cat.attributes.except('created_at', 'updated_at')})\n"
    

提交回复
热议问题