2012-06-01 30 views
1

我簡單SQLITE3數據庫如下:ActiveRecord的將不會更新

CREATE TABLE balances(
balance zilch 
); 

我的紅寶石如下:

require('active_record') 
ActiveRecord::Base.establish_connection(:database => "testbalance.db", :adapter => "sqlite3") 
class Balance < ActiveRecord::Base 
end 
x = Balance.new 
x.balance = 50 
x.save 

當我退出,然後回來,並在同一紅寶石進入再一次,(在我運行x.balance = 50之前)餘額是nil。爲什麼是這樣?爲什麼我的數據庫不能保存?

+0

JFI是一個rails應用程序或ruby的代碼,只是想知道它是否需要'sqlite3'可以看到它 – Viren

回答

2

如果輸入相同的代碼,那麼您將再次創建一個新對象。難怪它的餘額是nil

要檢查您的對象是否已保存,您可以(例如)在記錄創建之前和之後檢查Balance.count

0

這是一種使用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

我訓練你還是我喜歡?如果我在這裏請你錯了,版主會刪除它。我不想舉一個壞榜樣。