我在我的应用程序上创建新对象时遇到问题。显然,数据在我的 Sequel::Model 和 db 表本身之间的某处丢失,导致条目的 id 和所有属性都为 NULL。
这是我的模型:
class Wallet < Sequel::Model(:wallets)
attr_accessor :address, :balance
def validate
super
errors.add(:address, "Address can't be empty") if address.empty?
errors.add(:address, "Input address already exists in the db") unless Wallet.where(address: address).empty?
end
end
这是创建它的表的迁移:
Sequel.migration do
change do
create_table(:wallets) do
primary_key :id, unique: true
String :address
Integer :balance
end
end
end
我正在使用roda框架。这是 wallet_app.rb,其中创建了 Wallet 对象:
require 'roda'
require 'sequel'
require 'json'
DB = Sequel.connect('sqlite://database.sqlite3')
class WalletApp < Roda
require './lib/services/balance_service'
require './models/account'
route do |r|
...
r.post "wallets" do
address = r.params["address"]
balance = BalanceService.get_balance(address)
wallet = Wallet.new(address: address, balance: balance)
# Until here we have the attributes correctly set on wallet object
if wallet.valid? && wallet.save
# Now wallet is persisted in the db with an id but address and balance NULL
wallet.to_json
else
wallet.errors.to_json
end
end
end
end
正如上面类中的注释所指出的,该对象在插入数据库之前是有效的,并且属性显示正确设置。尽管如此,数据仍保留为所有属性 NULL。我假设迁移或模型定义中有错误,但我找不到任何错误。
如果有帮助,我还会在此处复制我的 Gemfile:
source "https://rubygems.org"
ruby '2.1.2'
gem 'roda'
gem 'sequel'
gem 'sqlite3'
gem 'httparty'
提前致谢