1

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

ntonnelier
  • 1,539
  • 3
  • 23
  • 49

2 Answers2

0

I am used to ActiveRecord and Rails, but according to Sequel documentation you could use validation_helpers plugin:

# model
class Wallet < Sequel::Model
  # plugin :validation_helpers
  def validate
    super
    validates_presence [:address, :balance], allow_nil: false
    validates_unique :address
  end
end

You could eventually set a unique constraint on the address column in the migration instead of uniqueness validation in the model. This method should prevent some side effects of custom validations (despite yours didn't seem bogus)

mabe02
  • 2,676
  • 2
  • 20
  • 35
0

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.

Jeremy Evans
  • 11,959
  • 27
  • 26