Reputation:
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.
Upvotes: 8
Views: 7364
Reputation: 1674
I could set default values with using defaults_setter.
For all models. (Call this before defining subclasses that want to use default_setter)
Sequel::Model.plugin :defaults_setter
Only for particular model.
Item.plugin :defaults_setter
or
Item class << Sequel::Model
plugin :defaults_setter
end
You can set default value like this.
Item.default_values[:name] = 'foobar'
Thank you.
Upvotes: 2
Reputation: 10676
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 method
def method_missing(type, name = nil, opts = {})
name ? column(name, type, opts) : super
end
please refer to sequel column for additional options
Upvotes: 4
Reputation: 12139
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
.
Upvotes: 8