How can default values in Sequel Models be set?

default, model, ruby, sequel

Solution

Subba's answer is the recommended way to do it in Sequel. It pushes the default into the database.

If you want to have defaults in the model instead of in the database, I recommend using a `before_create` or `after_initialize` hook to do them:

class Item < Sequel::Model
  def before_create # or after_initialize
    super
    self.name ||= 'Thing'
  end
end

The difference between `after_initialize` and `before_create` is when they are called. `before_create` is recommended, since it won't set the default until right before the database `INSERT` method is called. However, if you want:

Item.new.name == 'Thing'

then you have to use `after_initialize`.

Problem

Given the code below, how can default values be defined for the Model. (let's say the default for :name should be 'Thing'). ``` require 'pp' require 'sequel' DB = Sequel.sqlite DB.create_table :items do primary_key :id String :name end items = DB[ :items ] class Item < Sequel::Model end Item.create :name => 'foobar' Item.create pp Item.all # => # >> [#<Item @values={:name=>"foobar", :id=>1}>, # >> #<Item @values={:name=>nil, :id=>2}>] ``` So, I'd like to have the second created Item set to #<Item @values={:name=>"Thing", :id=>2}> rather than :name=>nil.

Original source