Module | Sequel::Model::InstanceMethods
In: | lib/sequel/model/base.rb

Sequel::Model instance methods that implement basic model functionality.

- All of the methods in HOOKS create instance methods that are called by Sequel when the appropriate action occurs. For example, when destroying a model object, Sequel will call before_destroy, do the destroy, and then call after_destroy.
- The following instance_methods all call the class method of the same name: columns, dataset, db, primary_key, db_schema.
- The following instance methods allow boolean flags to be set on a per-object basis: raise_on_save_failure, raise_on_typecast_failure, require_modification, strict_param_setting, typecast_empty_string_to_nil, typecast_on_assignment, use_transactions. If they are not used, the object will default to whatever the model setting is.

### Methods

== === [] []= autoincrementing_primary_key changed_columns delete destroy each eql? errors exists? hash id inspect keys lock! marshallable! modified! modified? new new? pk pk_hash refresh reload save save_changes set set_all set_except set_fields set_only this update update_all update_except update_fields update_only valid? validate

### External Aliases

class | -> | model
| class is defined in Object, but it is also a keyword, and since a lot of instance methods call class methods, this alias makes it so you can use model instead of self.class.

### Attributes

values | [R] | The hash of attribute values. Keys are symbols with the names of the underlying database columns.

### Public Class methods

new(values = {}, from_db = false) {|self if block_given?| ...}

Creates new instance and passes the given values to set. If a block is given, yield the instance to the block unless from_db is true. This method runs the after_initialize hook after it has optionally yielded itself to the block.

Arguments:

- values - should be a hash to pass to set.
- from_db - should only be set by Model.load, forget it exists.

[Source]

         # File lib/sequel/model/base.rb, line 555
    555:       def initialize(values = {}, from_db = false)
    556:         if from_db
    557:           @new = false
    558:           set_values(values)
    559:         else
    560:           @values = {}
    561:           @new = true
    562:           @modified = true
    563:           set(values)
    564:           changed_columns.clear
    565:           yield self if block_given?
    566:         end
    567:         after_initialize
    568:       end

### Public Instance methods

==(obj)

Alias of eql?

[Source]

         # File lib/sequel/model/base.rb, line 592
    592:       def ==(obj)
    593:         eql?(obj)
    594:       end

===(obj)

If pk is not nil, true only if the objects have the same class and pk. If pk is nil, false.

[Source]

         # File lib/sequel/model/base.rb, line 598
    598:       def ===(obj)
    599:         pk.nil? ? false : (obj.class == model) && (obj.pk == pk)
    600:       end

[](column)

Returns value of the column‘s attribute.

[Source]

         # File lib/sequel/model/base.rb, line 571
    571:       def [](column)
    572:         @values[column]
    573:       end

[]=(column, value)

Sets the value for the given column. If typecasting is enabled for this object, typecast the value based on the column‘s type. If this a a new record or the typecasted value isn‘t the same as the current value for the column, mark the column as changed.

[Source]

         # File lib/sequel/model/base.rb, line 579
    579:       def []=(column, value)
    580:         # If it is new, it doesn't have a value yet, so we should
    581:         # definitely set the new value.
    582:         # If the column isn't in @values, we can't assume it is
    583:         # NULL in the database, so assume it has changed.
    584:         v = typecast_value(column, value)
    585:         if new? || !@values.include?(column) || v != @values[column]
    586:           changed_columns << column unless changed_columns.include?(column)
    587:           @values[column] = v
    588:         end
    589:       end

autoincrementing_primary_key()

The autoincrementing primary key for this model object. Should be overridden if you have a composite primary key with one part of it being autoincrementing.

[Source]

         # File lib/sequel/model/base.rb, line 611
    611:       def autoincrementing_primary_key
    612:         primary_key
    613:       end

changed_columns()

The columns that have been updated. This isn‘t completely accurate, see Model#[]=.

[Source]

         # File lib/sequel/model/base.rb, line 617
    617:       def changed_columns
    618:         @changed_columns ||= []
    619:       end

delete()

Deletes and returns self. Does not run destroy hooks. Look into using destroy instead.

[Source]

         # File lib/sequel/model/base.rb, line 623
    623:       def delete
    624:         _delete
    625:         self
    626:       end

destroy(opts = {})

Like delete but runs hooks before and after delete. If before_destroy returns false, returns false without deleting the object the the database. Otherwise, deletes the item from the database and returns self. Uses a transaction if use_transactions is true or if the :transaction option is given and true.

[Source]

         # File lib/sequel/model/base.rb, line 634
    634:       def destroy(opts = {})
    635:         checked_save_failure{checked_transaction(opts){_destroy(opts)}}
    636:       end

each(&block)

Iterates through all of the current values using each.

Example:

      Ticket.find(7).each { |k, v| puts "#{k} => #{v}" }

[Source]

         # File lib/sequel/model/base.rb, line 642
    642:       def each(&block)
    643:         @values.each(&block)
    644:       end

eql?(obj)

Compares model instances by values.

[Source]

         # File lib/sequel/model/base.rb, line 647
    647:       def eql?(obj)
    648:         (obj.class == model) && (obj.values == @values)
    649:       end

errors()

Returns the validation errors associated with this object.

[Source]

         # File lib/sequel/model/base.rb, line 652
    652:       def errors
    653:         @errors ||= Errors.new
    654:       end

exists?()

Returns true when current instance exists, false otherwise. Generally an object that isn‘t new will exist unless it has been deleted.

[Source]

         # File lib/sequel/model/base.rb, line 659
    659:       def exists?
    660:         this.count > 0
    661:       end

hash()

Value that should be unique for objects with the same class and pk (if pk is not nil), or the same class and values (if pk is nil).

[Source]

         # File lib/sequel/model/base.rb, line 665
    665:       def hash
    666:         [model, pk.nil? ? @values.sort_by{|k,v| k.to_s} : pk].hash
    667:       end

id()

Returns value for the :id attribute, even if the primary key is not id. To get the primary key value, use pk.

[Source]

         # File lib/sequel/model/base.rb, line 671
    671:       def id
    672:         @values[:id]
    673:       end

inspect()

Returns a string representation of the model instance including the class name and values.

[Source]

         # File lib/sequel/model/base.rb, line 677
    677:       def inspect
    678:         "#<#{model.name} @values=#{inspect_values}>"
    679:       end

keys()

Returns the keys in values. May not include all column names.

[Source]

         # File lib/sequel/model/base.rb, line 682
    682:       def keys
    683:         @values.keys
    684:       end

lock!()

Refresh this record using for_update unless this is a new record. Returns self.

[Source]

         # File lib/sequel/model/base.rb, line 687
    687:       def lock!
    688:         new? ? self : _refresh(this.for_update)
    689:       end

marshallable!()

Remove elements of the model object that make marshalling fail. Returns self.

[Source]

         # File lib/sequel/model/base.rb, line 692
    692:       def marshallable!
    693:         @this = nil
    694:         self
    695:       end

modified!()

Explicitly mark the object as modified, so save_changes/update will run callbacks even if no columns have changed.

[Source]

         # File lib/sequel/model/base.rb, line 699
    699:       def modified!
    700:         @modified = true
    701:       end

modified?()

Whether this object has been modified since last saved, used by save_changes to determine whether changes should be saved. New values are always considered modified.

[Source]

         # File lib/sequel/model/base.rb, line 706
    706:       def modified?
    707:         @modified || !changed_columns.empty?
    708:       end

new?()

Returns true if the current instance represents a new record.

[Source]

         # File lib/sequel/model/base.rb, line 711
    711:       def new?
    712:         @new
    713:       end

pk()

Returns the primary key value identifying the model instance. Raises an error if this model does not have a primary key. If the model has a composite primary key, returns an array of values.

[Source]

         # File lib/sequel/model/base.rb, line 718
    718:       def pk
    719:         raise(Error, "No primary key is associated with this model") unless key = primary_key
    720:         key.is_a?(Array) ? key.map{|k| @values[k]} : @values[key]
    721:       end

pk_hash()

Returns a hash identifying the model instance. It should be true that:

     Model[model_instance.pk_hash] === model_instance

[Source]

         # File lib/sequel/model/base.rb, line 726
    726:       def pk_hash
    727:         model.primary_key_hash(pk)
    728:       end

refresh()

Reloads attributes from database and returns self. Also clears all cached association and changed_columns information. Raises an Error if the record no longer exists in the database.

[Source]

         # File lib/sequel/model/base.rb, line 733
    733:       def refresh
    734:         _refresh(this)
    735:       end

reload()

Alias of refresh, but not aliased directly to make overriding in a plugin easier.

[Source]

         # File lib/sequel/model/base.rb, line 738
    738:       def reload
    739:         refresh
    740:       end

save(*columns)

Creates or updates the record, after making sure the record is valid. If the record is not valid, or before_save, before_create (if new?), or before_update (if !new?) return false, returns nil unless raise_on_save_failure is true (if it is true, it raises an error). Otherwise, returns self. You can provide an optional list of columns to update, in which case it only updates those columns.

Takes the following options:

- :changed - save all changed columns, instead of all columns or the columns given
- :transaction - set to false not to use a transaction
- :validate - set to false not to validate the model before saving

[Source]

         # File lib/sequel/model/base.rb, line 755
    755:       def save(*columns)
    756:         opts = columns.last.is_a?(Hash) ? columns.pop : {}
    757:         if opts[:validate] != false and !valid?
    758:           raise(ValidationFailed.new(errors)) if raise_on_save_failure
    759:           return
    760:         end
    761:         checked_save_failure{checked_transaction(opts){_save(columns, opts)}}
    762:       end

save_changes(opts={})

Saves only changed columns if the object has been modified. If the object has not been modified, returns nil. If unable to save, returns false unless raise_on_save_failure is true.

[Source]

         # File lib/sequel/model/base.rb, line 767
    767:       def save_changes(opts={})
    768:         save(opts.merge(:changed=>true)) || false if modified?
    769:       end

set(hash)

Updates the instance with the supplied values with support for virtual attributes, raising an exception if a value is used that doesn‘t have a setter method (or ignoring it if strict_param_setting = false). Does not save the record.

[Source]

         # File lib/sequel/model/base.rb, line 775
    775:       def set(hash)
    776:         set_restricted(hash, nil, nil)
    777:       end

set_all(hash)

Set all values using the entries in the hash, ignoring any setting of allowed_columns or restricted columns in the model.

[Source]

         # File lib/sequel/model/base.rb, line 781
    781:       def set_all(hash)
    782:         set_restricted(hash, false, false)
    783:       end

set_except(hash, *except)

Set all values using the entries in the hash, except for the keys given in except.

[Source]

         # File lib/sequel/model/base.rb, line 787
    787:       def set_except(hash, *except)
    788:         set_restricted(hash, false, except.flatten)
    789:       end

set_fields(hash, fields)

For each of the fields in the given array `fields`, call the setter method with the value of that `hash` entry for the field. Returns self.

[Source]

         # File lib/sequel/model/base.rb, line 793
    793:       def set_fields(hash, fields)
    794:         fields.each{|f| send("#{f}=", hash[f])}
    795:         self
    796:       end

set_only(hash, *only)

Set the values using the entries in the hash, only if the key is included in only.

[Source]

         # File lib/sequel/model/base.rb, line 800
    800:       def set_only(hash, *only)
    801:         set_restricted(hash, only.flatten, false)
    802:       end

this()

Returns (naked) dataset that should return only this instance.

[Source]

         # File lib/sequel/model/base.rb, line 805
    805:       def this
    806:         @this ||= model.dataset.filter(pk_hash).limit(1).naked
    807:       end

update(hash)

Runs set with the passed hash and then runs save_changes.

[Source]

         # File lib/sequel/model/base.rb, line 810
    810:       def update(hash)
    811:         update_restricted(hash, nil, nil)
    812:       end

update_all(hash)

Update all values using the entries in the hash, ignoring any setting of allowed_columns or restricted columns in the model.

[Source]

         # File lib/sequel/model/base.rb, line 816
    816:       def update_all(hash)
    817:         update_restricted(hash, false, false)
    818:       end

update_except(hash, *except)

Update all values using the entries in the hash, except for the keys given in except.

[Source]

         # File lib/sequel/model/base.rb, line 822
    822:       def update_except(hash, *except)
    823:         update_restricted(hash, false, except.flatten)
    824:       end

update_fields(hash, fields)

Update the instances values by calling `set_fields` with the `hash` and `fields`, then save any changes to the record. Returns self.

[Source]

         # File lib/sequel/model/base.rb, line 828
    828:       def update_fields(hash, fields)
    829:         set_fields(hash, fields)
    830:         save_changes
    831:       end

update_only(hash, *only)

Update the values using the entries in the hash, only if the key is included in only.

[Source]

         # File lib/sequel/model/base.rb, line 835
    835:       def update_only(hash, *only)
    836:         update_restricted(hash, only.flatten, false)
    837:       end

valid?()

Validates the object and returns true if no errors are reported.

[Source]

         # File lib/sequel/model/base.rb, line 847
    847:       def valid?
    848:         errors.clear
    849:         if before_validation == false
    850:           save_failure(:validation) if raise_on_save_failure
    851:           return false
    852:         end
    853:         validate
    854:         after_validation
    855:         errors.empty?
    856:       end

validate()

Validates the object. If the object is invalid, errors should be added to the errors attribute. By default, does nothing, as all models are valid by default. See the "Model Validations" guide. for details about validation.

[Source]

         # File lib/sequel/model/base.rb, line 843
    843:       def validate
    844:       end

[Validate]