Ruby-on-rails 从数据库中已有的数据创建种子文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4393246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:50:43  来源:igfitidea点击:

Create seed file from data already in the database

ruby-on-railsactiverecordruby-on-rails-3rake

提问by swrobel

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 the seeds.rb format for me from this table?

我正在使用 Rails 3.0.3,并且数据库中已经有我的“类别”表的数据,但想从中创建一个种子文件。是否有任何 rake 任务会从这张表中为我生成种子.rb 格式?

回答by John Peterson

There is a gem called seed_dump, which will do exactly what you want:

有一个名为 的 gem seed_dump,它可以完全满足您的需求:

回答by Brian

Not sure about any existing rake tasks, but you can try running something like this in the rails console & paste the results into your seeds.rb file

不确定是否有任何现有的 rake 任务,但您可以尝试在 Rails 控制台中运行类似的内容并将结果粘贴到您的 seed.rb 文件中

(warning:dirty & untested)

警告:脏且未经测试)

c = Category.all

c.each do |cat|
  puts "Category.create(:name => '#{cat.name}')"
end

Adjust for any additional fields you may have.

调整您可能拥有的任何其他字段。

Hope this helps.

希望这可以帮助。

回答by MattSlay

I've used YamlDb to dump data from my development db and then load it up to another server. It dumps the data to a Yaml file, which will be used any time you want to use db:load to push it up to any other db server.

我使用 YamlDb 从我的开发数据库中转储数据,然后将其加载到另一台服务器。它将数据转储到 Yaml 文件,该文件将在您想使用 db:load 将其推送到任何其他数据库服务器时使用。

https://github.com/ludicast/yaml_db

https://github.com/ludicast/yaml_db

回答by Ruby Racer

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

老问题,我有一个基于@Brian 回答的新问题。

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"