Whether to raise an error when unable to typecast data for a column
(default: true). This should be set to false if you want to use
validations to display nice error messages to the user (e.g. most web
applications). You can use the validates_schema_types validation (from the
validation_helpers plugin) in connection with this setting to check for
typecast failures during validation.

Whether new/set/update and their variants should raise an error if an
invalid key is used. A key is invalid if no setter method exists for that
key or the access to the setter method is restricted (e.g. due to it being
a primary key field). If set to false, silently skip any key where the
setter method doesn't exist or access to it is restricted.

Whether to typecast the empty string ('') to nil for columns that
are not string or blob. In most cases the empty string would be the way to
specify a NULL SQL value in string form (nil.to_s == ''), and an
empty string would not usually be typecast correctly for other types, so
the default is true.

Whether to enable the after_commit and after_rollback hooks when
saving/destroying instances. On by default, can be turned off for
performance reasons or when using prepared transactions (which aren't
compatible with after commit/rollback).

Whether to use a transaction by default when saving/deleting records
(default: true). If you are sending database queries in before_* or after_*
hooks, you shouldn't change the default setting without a good reason.

Instance Method Details

Returns the first record from the database matching the conditions. If a
hash is given, it is used as the conditions. If another object is given,
it finds the first record whose primary key(s) match the given argument(s).
If no object is returned by the dataset, returns nil.

Initializes a model instance as an existing record. This constructor is
used by Sequel to initialize model instances when fetching records.
Requires that values be a hash where all keys are symbols. It probably
should not be used by external code.

Returns the columns in the result set in their original order. Generally,
this will use the columns determined via the database schema, but in
certain cases (e.g. models that are based on a joined dataset) it will use
Dataset#columns to find the columns.

Returns the dataset associated with the Model class. Raises an
Error if there is no associated dataset for this class. In most
cases, you don't need to call this directly, as Model proxies many
dataset methods to the underlying dataset.

Extend the dataset with a module, similar to adding a plugin with the
methods defined in DatasetMethods. This is the recommended way to add
methods to model datasets.

If an argument, it should be a module, and is used to extend the underlying
dataset. Otherwise an anonymous module is created, and if a block is
given, it is module_evaled, allowing you do define dataset methods directly
using the standard ruby def syntax. Returns the module given or the
anonymous module created.

Any public methods in the dataset module will have class methods created
that call the method on the dataset, assuming that the class method is not
already defined.

200
201
202
203
204
205
206
207
208
209
210
211

# File 'lib/sequel/model/base.rb', line 200defdataset_module(mod=nil)ifmodraiseError,"can't provide both argument and block to Model.dataset_module"ifblock_given?dataset_extend(mod)modelse@dataset_module||=DatasetModule.new(self)@dataset_module.module_eval(&Proc.new)ifblock_given?dataset_extend(@dataset_module)@dataset_moduleendend

Returns the database associated with the Model class. If this model
doesn't have a database associated with it, assumes the
superclass's database, or the first object in Sequel::DATABASES. If no
Sequel::Database object has been created, raises an error.

# File 'lib/sequel/model/base.rb', line 223defdbreturn@dbif@db@db=self==Model?Sequel.synchronize{DATABASES.first}:superclass.dbraise(Error,"No database associated with #{self}: have you called Sequel.connect or #{self}.db= ?")unless@db@dbend

Sets the database associated with the Model class. If the model has an
associated dataset, sets the model's dataset to a dataset on the new
database with the same options used by the current dataset. This can be
used directly on Sequel::Model to set the default database to be used by
subclasses, or to override the database used for specific models:

Sequel::Model.db=DB1Artist.db=DB2

Note that you should not use this to change the model's database at
runtime. If you have that need, you should look into Sequel's sharding
support.

Returns the cached schema information if available or gets it from the
database. This is a hash where keys are column symbols and values are
hashes of information related to the column. See Database#schema.

If a block is given, define a method on the dataset (if the model currently
has an dataset) with the given argument name using the given block. Also
define a class method on the model that calls the dataset method. Stores
the method name and block so that it can be reapplied if the model's
dataset changes.

If a block is not given, just define a class method on the model for each
argument that calls the dataset method of the same argument name.

It is recommended that you define methods inside a block passed to
#dataset_module instead of using this method, as #dataset_module allows you
to use normal ruby def syntax.

# Add new dataset method and class method that calls it
Artist.def_dataset_method(:by_name){order(:name)}Artist.filter(:name.like('A%')).by_nameArtist.by_name.filter(:name.like('A%'))# Just add a class method that calls an existing dataset method
Artist.def_dataset_method(:server!)Artist.server!(:server1)

# File 'lib/sequel/model/base.rb', line 291defdef_dataset_method(*args,&block)raise(Error,"No arguments given")ifargs.empty?ifblockraise(Error,"Defining a dataset method using a block requires only one argument")ifargs.length>1dataset_module{define_method(args.first,&block)}elseargs.each{|arg|def_model_dataset_method(arg)}endend

Like find but invokes create with given conditions when record
does not exist. Unlike find in that the block used in this method
is not passed to find, but instead is passed to create
only if find does not return an object.

Note that if you pass your own block, you are responsible for manually
setting limits if necessary (as shown above).

Options:

:arity

When using a symbol method name, this specifies the arity of the method.
This should be used if if the method accepts an arbitrary number of
arguments, or the method has default argument values. Note that if the
method is defined as a dataset method, the class method Sequel creates
accepts an arbitrary number of arguments, so you should use this option in
that case. If you want to handle multiple possible arities, you need to
call the finder method multiple times with unique :arity and :name methods
each time.

:name

The name of the method to create. This must be given if you pass a block.
If you use a symbol, this defaults to the symbol prefixed by the type.

:mod

The module in which to create the finder method. Defaults to the singleton
class of the model.

:type

The type of query to run. Can be :first, :each, :all, or :get, defaults to
:first.

Caveats:

This doesn't handle all possible cases. For example, if you have a
method such as:

defArtist.by_name(name)name?where(:name=>name):exclude(:name=>nil)end

Then calling a finder without an argument will not work as you expect.

Artist.finder:by_nameArtist.by_name(nil).first# WHERE (name IS NOT NULL)
Artist.first_by_name(nil)# WHERE (name IS NULL)

# File 'lib/sequel/model/base.rb', line 393deffinder(meth=OPTS,opts=OPTS,&block)ifblockraiseError,"cannot pass both a method name argument and a block of Model.finder"unlessmeth.is_a?(Hash)raiseError,"cannot pass two option hashes to Model.finder"unlessopts.equal?(OPTS)opts=methraiseError,"must provide method name via :name option when passing block to Model.finder"unlessmeth_name=opts[:name]endtype=opts.fetch(:type,:first)unlessprepare=opts[:prepare]raiseError,":type option to Model.finder must be :first, :all, :each, or :get"unlessFINDER_TYPES.include?(type)endlimit1=type==:first||type==:getmeth_name||=opts[:name]||:#{type}_#{meth}"argn=lambdado|model|ifarity=opts[:arity]arityelsemethod=block||model.method(meth)(method.arity<0?method.arity.abs-1:method.arity)endendloader_proc=ifprepareprocdo|model|args=prepare_method_args('$a',argn.call(model))ds=ifblockmodel.instance_exec(*args,&block)elsemodel.send(meth,*args)endds=ds.limit(1)iflimit1model_name=model.nameifmodel_name.to_s.empty?model_name=model.object_idelsemodel_name=model_name.gsub(/\W/,'_')endds.prepare(type,:#{model_name}_#{meth_name}")endelseprocdo|model|n=argn.call(model)block||=lambdado|pl,model2|args=(0...n).map{pl.arg}ds=model2.send(meth,*args)ds=ds.limit(1)iflimit1dsendSequel::Dataset::PlaceholderLiteralizer.loader(model,&block)endendSequel.synchronize{@finder_loaders[meth_name]=loader_proc}mod=opts[:mod]||(class<<self;self;end)ifpreparedef_prepare_method(mod,meth_name)elsedef_finder_method(mod,meth_name,type)endend

Loads a plugin for use with the model class, passing optional arguments to
the plugin. If the plugin is a module, load it directly. Otherwise,
require the plugin from either sequel/plugins/#plugin or
sequel_#plugin, and then attempt to load the module using a the camelized
plugin name under Sequel::Plugins.

Similar to finder, but uses a prepared statement instead of a placeholder
literalizer. This makes the SQL used static (cannot vary per call), but
allows binding argument values instead of literalizing them into the SQL
query string.

If a block is used with this method, it is instance_execed by the model,
and should accept the desired number of placeholder arguments.

The options are the same as the options for finder, with the following
exception:

:type

Specifies the type of prepared statement to create

626
627
628
629
630
631
632
633
634

# File 'lib/sequel/model/base.rb', line 626defprepared_finder(meth=OPTS,opts=OPTS,&block)ifblockraiseError,"cannot pass both a method name argument and a block of Model.finder"unlessmeth.is_a?(Hash)meth=meth.merge(:prepare=>true)elseopts=opts.merge(:prepare=>true)endfinder(meth,opts,&block)end

Returns primary key attribute hash. If using a composite primary key value
such be an array with values for each primary key in the correct order.
For a standard primary key, value should be an object with a compatible
type for the key. If the model does not have a primary key, raises an
Error.

# File 'lib/sequel/model/base.rb', line 582defprimary_key_hash(value)casekey=@primary_keywhenSymbol{key=>value}whenArrayhash={}key.zip(Array(value)){|k,v|hash[k]=v}hashelseraise(Error,"#{self} does not have a primary key")endend

Return a hash where the keys are qualified column references. Uses the
given qualifier if provided, or the table_name otherwise. This is useful if
you plan to join other tables to this table and you want the column
references to be qualified.

# File 'lib/sequel/model/base.rb', line 602defqualified_primary_key_hash(value,qualifier=table_name)casekey=@primary_keywhenSymbol{SQL::QualifiedIdentifier.new(qualifier,key)=>value}whenArrayhash={}key.zip(Array(value)){|k,v|hash[SQL::QualifiedIdentifier.new(qualifier,k)]=v}hashelseraise(Error,"#{self} does not have a primary key")endend

Restrict the setting of the primary key(s) when using mass assignment (e.g.
set). Because this is the default, this only make sense to use in
a subclass where the parent class has used unrestrict_primary_key.

Set the columns to allow when using mass assignment (e.g. set).
Using this means that any columns not listed here will not be modified. If
you have any virtual setter methods (methods that end in =) that you want
to be used during mass assignment, they need to be listed here as well
(without the =).

It may be better to use a method such as set_only or
set_fields that lets you specify the allowed fields per call.

Sets the dataset associated with the Model class. ds can be a
Symbol, LiteralString, SQL::Identifier,
SQL::QualifiedIdentifier, SQL::AliasedExpression (all
specifying a table name in the current database), or a Dataset. If
a dataset is used, the model's database is changed to the database of
the given dataset. If a dataset is not used, a dataset is created from the
current database with the table name given. Other arguments raise an
Error. Returns self.

This changes the row_proc of the dataset to return model objects and
extends the dataset with the dataset_method_modules. It also attempts to
determine the database schema for the model, based on the given dataset.

Artist.set_dataset(:tbl_artists)Artist.set_dataset(DB[:artists])

Note that you should not use this to change the model's dataset at
runtime. If you have that need, you should look into Sequel's sharding
support.

Sets the primary key for this model. You can use either a regular or a
composite primary key. To not use a primary key, set to nil or use
no_primary_key. On most adapters, Sequel can automatically
determine the primary key to use, so this method is not needed often.