views:

291

answers:

2

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.

+2  A: 
DB.create_table :items do
        primary_key :id
        String :name,:default => 'Thing'
end

should do the trick

from the sequel Sequel::Database source create_table block is evaluated inside Schema::Generator

def create_table(name, options={}, &block)
    options = {:generator=>options} if options.is_a?(Schema::Generator)
    generator = options[:generator] || Schema::Generator.new(self, &block)
    create_table_from_generator(name, generator, options)
    create_table_indexes_from_generator(name, generator, options)
end

inside Schema::Generator class method_missing handles String,text,boolean,number are handled by column mehtod

def method_missing(type, name = nil, opts = {})
     name ? column(name, type, opts) : super
end

please refert to sequel column for additional options

Subba Rao
+1  A: 

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.

Jeremy Evans