【问题标题】:I can't populate data from seed.rb我无法从 seed.rb 填充数据
【发布时间】:2017-02-11 09:10:42
【问题描述】:

我无法从seed.rb 填充我的数据,当我使用rake db:seed 时没有任何反应。

  • 使用 Rails 5。
  • 来自 Rails 4 的数据

我可以在 Rails 5 中使用这种结构吗?

Product.delete_all
Product.create!(title: 'CoffeeScript',
  description: 
    %{<p>
        CoffeeScript is JavaScript done right. It provides all of JavaScript\'s
    functionality wrapped in a cleaner, more succinct syntax. In the first
    book on this exciting new language, CoffeeScript guru Trevor Burnham
    shows you how to hold onto all the power and flexibility of JavaScript
    while writing clearer, cleaner, and safer code.
      </p>},
  image_url:   'cs.jpg',    
  price: 36.00)
# . . .
Product.create!(title: 'Programming Ruby 1.9 & 2.0',
  description:
    %{<p>
        Ruby is the fastest growing and most exciting dynamic language
        out there. If you need to get working programs delivered fast,
        you should add Ruby to your toolbox.
      </p>},
  image_url: 'ruby.jpg',
  price: 49.95)



Product.create!(title: 'Rails Test Prescriptions',
  description: 
    %{<p>
        <em>Rails Test Prescriptions</em> is a comprehensive guide to testing
        Rails applications, covering Test-Driven Development from both a
        theoretical perspective (why to test) and from a practical perspective
        (how to test effectively). It covers the core Rails testing tools and
        procedures for Rails 2 and Rails 3, and introduces popular add-ons,
        including Cucumber, Shoulda, Machinist, Mocha, and Rcov.
      </p>},
  image_url: 'rtp.jpg',
  price: 34.95)

【问题讨论】:

  • 播种从 4 到 5 的工作方式没有变化,因此错误一定在其他地方。您尝试向文件添加一些简单的调试,看看它是否正在运行。就像顶部的puts 'first line',然后应该在控制台中看到。

标签: ruby-on-rails ruby-on-rails-5 seed


【解决方案1】:

种子数据加载和验证

创建一个测试应用程序

$ rails new seedtest
$ cd seedtest

添加产品型号

$ rails g model product title description image_url price:decimal
$ rails db:migrate

准备 db/seeds.rb 文件

puts 'start loading data'
copy and paste your loading code into db/seeds.rb
puts 'finish loading data'

加载种子数据

$ rails db:seed
start Loading data
finish Loading data

验证

$ rails db
sqlite> select * from products;



1|CoffeeScript|
    CoffeeScript is JavaScript done right. It provides all of    JavaScript's
functionality wrapped in a cleaner, more succinct syntax. In the first
book on this exciting new language, CoffeeScript guru Trevor Burnham
shows you how to hold onto all the power and flexibility of JavaScript
while writing clearer, cleaner, and safer code.
  |cs.jpg|36|2017-02-11 10:44:38.648505|2017-02-11 10:44:38.648505
...
...
More data

.exit    # when you've finished

Code on github - with commits using each title

【讨论】:

  • 我尝试了 'rails db:seed' 而不是 'rake db:seed',我也使用了该示例,但仍然无法正常工作。 :|当我将'rails db:seed'放入命令时,没有打印任何内容:/
  • rake db:seed 仍然可以在 Rails 5 上使用,它没有被弃用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
相关资源
最近更新 更多