简体   繁体   English

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

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

Okay so I have model, and I populated my sqlite database in my seeds.rb here is the code 好的,所以我有了模型,然后将我的sqlite数据库填充到了seeds.rb中,这是代码

~/PeriodicTable/db/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

Then I tried to access it in my rspec and I keep getting nil, this is my rspec 然后我尝试在我的rspec中访问它,但我不断得到nil,这是我的rspec

~/PeriodicTable/spec/models/element_spec.rb 〜/元素周期表/规格/型号/ 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

However Element.find_by keep returning nil no matter what I put in. My database is populated for sure because I checked. 但是,无论我输入什么内容,Element.find_by都将始终返回nil。可以肯定地填充了我的数据库,因为我进行了检查。 When I do Element.find_by in my rails console it works just fine. 当我在rails console执行Element.find_by ,它工作正常。 I can get all the elements correctly in my rails console however when I put it anywhere in my rails app Element.find_by always returns nil 我可以在rails控制台中正确获取所有元素,但是当我将其放置在rails应用程序中的任何位置时, Element.find_by始终返回nil

here is also my model class if its any relevance 这也是我的模型课,如果有任何相关性

~/PeriodicTable/app/models/element.rb 〜/元素周期表/应用/模型/ element.rb

class Element < ActiveRecord::Base
end

Rails maintains different db's for production, development, and test. Rails维护用于生产,开发和测试的不同数据库。 This means that the data you think should be there exists in your development db. 这意味着您开发数据库中应该存在您认为应该存在的数据。 If you want to access data in tests, you need to save it in your testing environment. 如果要访问测试中的数据,则需要将其保存在测试环境中。 Consider using FactoryGirl to create objects in your test database. 考虑使用FactoryGirl在测试数据库中创建对象。

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

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