Search code examples
rubysqlitesequelroda

Ruby Sequel SQLite3 app saves valid objects to database with NULL attributes


I'm having problems creating new objects on my application. Apparently the data gets lost somewhere between my Sequel::Model and the db table itself, resulting in entries with an id and all attributes in NULL.

This is my model:

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

And this is the migration that created it's table:

Sequel.migration do
  change do
    create_table(:wallets) do
      primary_key :id, unique: true
      String :address
      Integer :balance
    end
  end
end

I'm using roda framework. Here is wallet_app.rb, where Wallet objects are created:

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

As pointed out in the comments in the class above, the object is valid before inserting in the DB and the attributes appear correctly set. Still, the data is persisted as all attributes NULL. I'm assuming an error in the migration or the Model definition but I could not find any.

In case it helps, I copy also my Gemfile here:

source "https://rubygems.org"

ruby '2.1.2'

gem 'roda'
gem 'sequel'
gem 'sqlite3'
gem 'httparty'

Thanks in advance


Solution

  • You should remove attr_accessor :address, :balance, that is what is breaking things. Sequel::Model stores attributes in the values hash, not as separate instance variables.