【问题标题】:How do I access contents of my database in rails?如何在 Rails 中访问我的数据库的内容?
【发布时间】:2014-11-23 08:58:33
【问题描述】:

好的,所以我有模型,我在我的种子中填充了我的 sqlite 数据库。这里是代码

~/PeriodicTable/db/seeds.rb

# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
#   Mayor.create(name: 'Emanuel', city: cities.first)
File.open("pt-data3.csv", 'r').each_line do |line|
    temp = line.split(',')
    Element.create(proton: temp[0].strip, symbol: temp[1].strip, name: temp[2].strip, mass: temp[3].strip)
end

然后我尝试在我的 rspec 中访问它,但我一直得到 nil,这是我的 rspec

~/PeriodicTable/spec/models/element_spec.rb

require 'rails_helper'

RSpec.describe Element, :type => :model do
    it "should contain the right elements" do
        expect(Element.find_by(proton: 1)).to include("Hydrogen")
    end
end

但是 Element.find_by 始终返回 nil 无论我输入什么。我的数据库肯定已填充,因为我检查了。当我在我的rails console 中执行Element.find_by 时,它工作得很好。我可以在 Rails 控制台中正确获取所有元素,但是当我将其放在 Rails 应用程序中的任何位置时 Element.find_by 总是返回 nil

这也是我的模型类,如果它有任何相关性

~/PeriodicTable/app/models/element.rb

class Element < ActiveRecord::Base
end

【问题讨论】:

    标签: ruby-on-rails sqlite rspec


    【解决方案1】:

    Rails 为生产、开发和测试维护不同的数据库。这意味着您认为应该存在的数据存在于您的开发数据库中。如果要在测试中访问数据,则需要将其保存在测试环境中。考虑使用 FactoryGirl 在您的测试数据库中创建对象。

    【讨论】:

    • 或者你可以运行 RAILS_ENV=test rake db:seed
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多