Module: Sequel::Model::InstanceMethods

Defined in:
lib/sequel/model/base.rb

Overview

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, 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.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#valuesObject (readonly)

The hash of attribute values. Keys are symbols with the names of the underlying database columns.



493
494
495
# File 'lib/sequel/model/base.rb', line 493

def values
  @values
end

Instance Method Details

#==(obj) ⇒ Object Also known as: eql?

Compares model instances by values.



543
544
545
# File 'lib/sequel/model/base.rb', line 543

def ==(obj)
  (obj.class == model) && (obj.values == @values)
end

#===(obj) ⇒ Object

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



550
551
552
# File 'lib/sequel/model/base.rb', line 550

def ===(obj)
  pk.nil? ? false : (obj.class == model) && (obj.pk == pk)
end

#[](column) ⇒ Object

Returns value of the column’s attribute.



520
521
522
# File 'lib/sequel/model/base.rb', line 520

def [](column)
  @values[column]
end

#[]=(column, value) ⇒ Object

Sets value of the column’s attribute and marks the column as changed. If the column already has the same value, this is a no-op. Note that changing a columns value and then changing it back will cause the column to appear in changed_columns. Similarly, providing a value that is different from the column’s current value but is the same after typecasting will also cause changed_columns to include the column.



531
532
533
534
535
536
537
538
539
540
# File 'lib/sequel/model/base.rb', line 531

def []=(column, value)
  # If it is new, it doesn't have a value yet, so we should
  # definitely set the new value.
  # If the column isn't in @values, we can't assume it is
  # NULL in the database, so assume it has changed.
  if new? || !@values.include?(column) || value != @values[column]
    changed_columns << column unless changed_columns.include?(column)
    @values[column] = typecast_value(column, value)
  end
end

#associationsObject

The current cached associations. A hash with the keys being the association name symbols and the values being the associated object or nil (many_to_one), or the array of associated objects (*_to_many).



563
564
565
# File 'lib/sequel/model/base.rb', line 563

def associations
  @associations ||= {}
end

#autoincrementing_primary_keyObject

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.



570
571
572
# File 'lib/sequel/model/base.rb', line 570

def autoincrementing_primary_key
  primary_key
end

#changed_columnsObject

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



576
577
578
# File 'lib/sequel/model/base.rb', line 576

def changed_columns
  @changed_columns ||= []
end

#deleteObject

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



582
583
584
585
# File 'lib/sequel/model/base.rb', line 582

def delete
  this.delete
  self
end

#destroyObject

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.



592
593
594
# File 'lib/sequel/model/base.rb', line 592

def destroy
  use_transactions ? db.transaction{_destroy} : _destroy
end

#each(&block) ⇒ Object

Iterates through all of the current values using each.

Example:

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


600
601
602
# File 'lib/sequel/model/base.rb', line 600

def each(&block)
  @values.each(&block)
end

#errorsObject

Returns the validation errors associated with this object.



605
606
607
# File 'lib/sequel/model/base.rb', line 605

def errors
  @errors ||= Errors.new
end

#exists?Boolean

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

Returns:

  • (Boolean)


612
613
614
# File 'lib/sequel/model/base.rb', line 612

def exists?
  this.count > 0
end

#hashObject

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).



618
619
620
# File 'lib/sequel/model/base.rb', line 618

def hash
  [model, pk.nil? ? @values.sort_by{|k,v| k.to_s} : pk].hash
end

#idObject

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



624
625
626
# File 'lib/sequel/model/base.rb', line 624

def id
  @values[:id]
end

#initialize(values = {}, from_db = false) ⇒ Object

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.



505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/sequel/model/base.rb', line 505

def initialize(values = {}, from_db = false)
  if from_db
    @new = false
    @values = values
  else
    @values = {}
    @new = true
    set(values)
    changed_columns.clear 
    yield self if block_given?
  end
  after_initialize
end

#inspectObject

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



630
631
632
# File 'lib/sequel/model/base.rb', line 630

def inspect
  "#<#{model.name} @values=#{inspect_values}>"
end

#keysObject

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



635
636
637
# File 'lib/sequel/model/base.rb', line 635

def keys
  @values.keys
end

#new?Boolean

Returns true if the current instance represents a new record.

Returns:

  • (Boolean)


640
641
642
# File 'lib/sequel/model/base.rb', line 640

def new?
  @new
end

#pkObject

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.

Raises:



647
648
649
650
# File 'lib/sequel/model/base.rb', line 647

def pk
  raise(Error, "No primary key is associated with this model") unless key = primary_key
  key.is_a?(Array) ? key.map{|k| @values[k]} : @values[key]
end

#pk_hashObject

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

Model[model_instance.pk_hash] === model_instance


655
656
657
# File 'lib/sequel/model/base.rb', line 655

def pk_hash
  model.primary_key_hash(pk)
end

#refreshObject

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.



662
663
664
# File 'lib/sequel/model/base.rb', line 662

def refresh
  _refresh(this)
end

#reloadObject

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



667
668
669
# File 'lib/sequel/model/base.rb', line 667

def reload
  refresh
end

#save(*columns) ⇒ Object

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



684
685
686
687
688
689
# File 'lib/sequel/model/base.rb', line 684

def save(*columns)
  opts = columns.last.is_a?(Hash) ? columns.pop : {}
  return save_failure(:invalid) if opts[:validate] != false and !valid?
  use_transaction = opts.include?(:transaction) ? opts[:transaction] : use_transactions
  use_transaction ? db.transaction(opts){_save(columns, opts)} : _save(columns, opts)
end

#save_changesObject

Saves only changed columns or does nothing if no columns are marked as chanaged. If no columns have been changed, returns nil. If unable to save, returns false unless raise_on_save_failure is true.



694
695
696
# File 'lib/sequel/model/base.rb', line 694

def save_changes
  save(:changed=>true) || false unless changed_columns.empty?
end

#set(hash) ⇒ Object

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.



702
703
704
# File 'lib/sequel/model/base.rb', line 702

def set(hash)
  set_restricted(hash, nil, nil)
end

#set_all(hash) ⇒ Object

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



708
709
710
# File 'lib/sequel/model/base.rb', line 708

def set_all(hash)
  set_restricted(hash, false, false)
end

#set_except(hash, *except) ⇒ Object

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



714
715
716
# File 'lib/sequel/model/base.rb', line 714

def set_except(hash, *except)
  set_restricted(hash, false, except.flatten)
end

#set_only(hash, *only) ⇒ Object

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



720
721
722
# File 'lib/sequel/model/base.rb', line 720

def set_only(hash, *only)
  set_restricted(hash, only.flatten, false)
end

#thisObject

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



725
726
727
# File 'lib/sequel/model/base.rb', line 725

def this
  @this ||= model.dataset.filter(pk_hash).limit(1).naked
end

#update(hash) ⇒ Object

Runs set with the passed hash and runs save_changes (which runs any callback methods).



730
731
732
# File 'lib/sequel/model/base.rb', line 730

def update(hash)
  update_restricted(hash, nil, nil)
end

#update_all(hash) ⇒ Object

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



736
737
738
# File 'lib/sequel/model/base.rb', line 736

def update_all(hash)
  update_restricted(hash, false, false)
end

#update_except(hash, *except) ⇒ Object

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



742
743
744
# File 'lib/sequel/model/base.rb', line 742

def update_except(hash, *except)
  update_restricted(hash, false, except.flatten)
end

#update_only(hash, *only) ⇒ Object

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



748
749
750
# File 'lib/sequel/model/base.rb', line 748

def update_only(hash, *only)
  update_restricted(hash, only.flatten, false)
end

#valid?Boolean

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

Returns:

  • (Boolean)


759
760
761
762
763
764
765
766
767
768
# File 'lib/sequel/model/base.rb', line 759

def valid?
  errors.clear
  if before_validation == false
    save_failure(:validation)
    return false
  end
  validate
  after_validation
  errors.empty?
end

#validateObject

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.



755
756
# File 'lib/sequel/model/base.rb', line 755

def validate
end