【发布时间】:2019-08-29 01:57:38
【问题描述】:
ruby -v 2.3.7(sqlite3 与较新的 ruby -v 存在兼容性问题)
sqlite3 -v 3.22sqlite -v 2.8lsb_release -a 18.04
我已经尽可能地压缩了代码。
def some_method(info_hash)
...
db.results_as_hash = true
sum = 0
db.transaction
db.execute2 "CREATE table if not exists a_table(Id INT PRIMARY KEY, Type TEXT, Month TEXT, Amount FLOAT, TOTAL FLOAT)"
db.execute2 "INSERT into a_table(Type, Month, Amount) values(:Type , :Month , :Amount)", info_hash[:category], info_hash[:month], info_hash[:amount]
get_amt = db.prepare "SELECT Amount from a_table WHERE Type = :Type"
get_amt.execute info_hash[:category]
get_amt.each do |g|
sum += g #here I get a NoMethodError for Nil:NilClass
end
db.execute2 "INSERT into bills(Total) values(:sum)", sum
db.commit
...
end
我主要使用execute2 方法。我依赖 execute 方法,我需要忽略标题,例如在我的 get_amt.each 块中。
我想sum Amount 列 Type。但是当我运行block 时遇到了NoMethodError。
完整的错误是:
undefined method '+' for nil:NilClass (NoMethodError)
请告知我哪里出错了。
编辑: 我重写了代码以反映@Shawn 的建议:
def some_method(info_hash)
...
db.transaction
db.execute2 "CREATE table if not exists a_table(Id INTEGER PRIMARY KEY, Type TEXT, Month TEXT, Amount FLOAT, Total FLOAT)"
db.execute2 "INSERT into a_table(Type, Month, Amount) values(:Type , :Month , :Amount)", info_hash[:category], info_hash[:month], info_hash[:amount]
get_amt = db.execute2 "SELECT sum(Amount) from a_table WHERE Type = :Type", info_hash[:category]
db.execute2 "INSERT into a_table(Total) values(:get_amt)", get_amt
db.commit
...
end
这会产生sqlite3 Exception Index out of range
【问题讨论】:
-
Ruby 2.7? Are you sure about that?
-
@anothermh 很抱歉那个错字(肯定错过了十几次!!!)已更正
-
Sqlite 2.8? ... 为什么?那是从 2003 年开始的!
-
为什么不
SELECT sum(amount) FROM a_table WHERE ...? -
哦!返回的行中的金额是否有空值?
标签: ruby sqlite each nomethoderror