這是一種使用Active Record的舊演示方式,對於生產不太有用。它會讓你開始。我的代碼將不需要sqlite3 gem進行連接。我認爲Active Record會包含它,如果你使用:適配器哈希條目。當然,你需要安裝它,但在Active Record的代碼中並不需要它。只需嘗試一下,不需要看到。如果您仍然有疑問,請取消安裝gem,以獲得樂趣。還有更多的Active Record命名空間和方法,您應該嘗試一下,特別是那些檢查數據庫是否已經存在的方法。然後通過創建一個。 以下是Metaprogramming Ruby一書中的一些示例代碼。
#---
# Excerpted from "Metaprogramming Ruby",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/ppmetr2 for more book information.
#---
# Create a new database each time
File.delete 'dbfile' if File.exist? 'dbfile'
require 'active_record'
ActiveRecord::Base.establish_connection :adapter => "sqlite3",
:database => "dbfile.sqlite3"
# Initialize the database schema
ActiveRecord::Base.connection.create_table :ducks do |t|
t.string :name
end
class Duck < ActiveRecord::Base
validate do
errors.add(:base, "Illegal duck name.") unless name[0] == 'D'
end
end
my_duck = Duck.new
my_duck.name = "Donald"
my_duck.valid? # => true
my_duck.save!
require_relative '../test/assertions'
assert my_duck.valid?
bad_duck = Duck.new(:name => "Ronald")
assert !bad_duck.valid?
duck_from_database = Duck.first
duck_from_database.name # => "Donald"
assert_equals "Donald", duck_from_database.name
duck_from_database.delete
File.delete 'dbfile' if File.exist? 'dbfile'
此代碼在使用後刪除數據庫文件,這也不是很好的持久性。但是你明白這一點只是爲了測試斷言。當你改變餘額時,你可以嘗試一下。
你想要其他代碼嗎? https://pragprog.com/book/ppmetr/metaprogramming-ruby
我訓練你還是我喜歡?如果我在這裏請你錯了,版主會刪除它。我不想舉一個壞榜樣。
JFI是一個rails應用程序或ruby的代碼,只是想知道它是否需要'sqlite3'可以看到它 – Viren