我刚刚开始学习 ActiveRecord,我只是在尝试一些小事情来弄清楚一切是如何工作的。我刚刚在以下 sqlite3 数据库上尝试了以下代码。
红宝石:
class Balances < ActiveRecord::Base
def initialize
@balance = 50
update_attribute(:balance, @balance)
end
def withdraw amount
update_attribute(:balance, @balance-amount)
end
end
SQL:
CREATE TABLE balance(
balance 50
);
当我写:
balance = Balances.new
我得到:
NoMethodError: undefined method `delete' for nil:NilClass
from /Users/Solomon/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/attribute_methods/write.rb:28:in `write_attribute'
from /Users/Solomon/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/attribute_methods/dirty.rb:67:in `write_attribute'
from /Users/Solomon/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/attribute_methods/write.rb:14:in `balance='
from /Users/Solomon/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/persistence.rb:180:in `update_attribute'
为什么是这样?难道我做错了什么?