繁体   English   中英

如何在Rails中访问数据库的内容?

[英]How do I access contents of my database in rails?

好的,所以我有了模型,然后将我的sqlite数据库填充到了seeds.rb中,这是代码

〜/元素周期表/分贝/ 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

〜/元素周期表/规格/型号/ 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

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

〜/元素周期表/应用/模型/ element.rb

class Element < ActiveRecord::Base
end

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM