1

我的简单Sqlite3数据库如下:

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

当我退出并返回并再次输入相同的 Ruby 时,起初(在我运行之前x.balance = 50)余额为nil. 为什么是这样?为什么我的数据库没有保存?

4

2 回答 2

2

If you enter the same code, then you're creating a new object again. No wonder its balance is nil.

To check that your object is saved, you can (for example) check Balance.count before and after record creation.

于 2012-06-01T20:30:17.660 回答
0

这是一种使用 Active Record 的旧演示方式,对生产不是很有用。它会让你开始。我的代码将在不需要 sqlite3 gem 的情况下建立连接。我认为如果您使用 :adapter 哈希条目,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'

此代码在使用后删除了 db 文件,这也不是很好的持久性。但是你明白了,因为它只是为了测试断言。您可以在更改余额时尝试确定。

你想要剩下的代码吗?https://pragprog.com/book/ppmetr/metaprogramming-ruby

我是在训练你还是像我一样?如果我在这里错了请版主删除此内容。我不想树立一个坏榜样。

于 2015-02-06T04:04:49.550 回答