Module Sequel::Model::InstanceMethods
In: lib/sequel/model/base.rb
lib/sequel/model/deprecated.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, 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

==   ===   []   []=   associations   changed_columns   dataset   delete   destroy   each   eql?   errors   exists?   hash   id   inspect   keys   new   new?   pk   pk_hash   refresh   reload   save   save!   save_changes   set   set_all   set_except   set_only   set_values   set_with_params   str_columns   this   update   update_all   update_except   update_only   update_values   update_with_params   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

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 503
503:       def initialize(values = {}, from_db = false)
504:         if from_db
505:           @new = false
506:           @values = values
507:         else
508:           @values = {}
509:           @new = true
510:           set(values)
511:           changed_columns.clear 
512:           yield self if block_given?
513:         end
514:         after_initialize
515:       end

Public Instance methods

Compares model instances by values.

[Source]

     # File lib/sequel/model/base.rb, line 541
541:       def ==(obj)
542:         (obj.class == model) && (obj.values == @values)
543:       end

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 548
548:       def ===(obj)
549:         pk.nil? ? false : (obj.class == model) && (obj.pk == pk)
550:       end

Returns value of the column‘s attribute.

[Source]

     # File lib/sequel/model/base.rb, line 518
518:       def [](column)
519:         @values[column]
520:       end

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.

[Source]

     # File lib/sequel/model/base.rb, line 529
529:       def []=(column, value)
530:         # If it is new, it doesn't have a value yet, so we should
531:         # definitely set the new value.
532:         # If the column isn't in @values, we can't assume it is
533:         # NULL in the database, so assume it has changed.
534:         if new? || !@values.include?(column) || value != @values[column]
535:           changed_columns << column unless changed_columns.include?(column)
536:           @values[column] = typecast_value(column, value)
537:         end
538:       end

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

[Source]

     # File lib/sequel/model/base.rb, line 561
561:       def associations
562:         @associations ||= {}
563:       end

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

[Source]

     # File lib/sequel/model/base.rb, line 567
567:       def changed_columns
568:         @changed_columns ||= []
569:       end

[Source]

     # File lib/sequel/model/deprecated.rb, line 131
131:       def dataset
132:         Deprecation.deprecate('Sequel::Model#dataset', 'Use model_object.model.dataset')
133:         model.dataset
134:       end

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

[Source]

     # File lib/sequel/model/base.rb, line 573
573:       def delete
574:         this.delete
575:         self
576:       end

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.

[Source]

     # File lib/sequel/model/base.rb, line 583
583:       def destroy
584:         use_transactions ? db.transaction{_destroy} : _destroy
585:       end

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 591
591:       def each(&block)
592:         @values.each(&block)
593:       end
eql?(obj)

Alias for #==

Returns the validation errors associated with this object.

[Source]

     # File lib/sequel/model/base.rb, line 596
596:       def errors
597:         @errors ||= Errors.new
598:       end

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 603
603:       def exists?
604:         this.count > 0
605:       end

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 609
609:       def hash
610:         [model, pk.nil? ? @values.sort_by{|k,v| k.to_s} : pk].hash
611:       end

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 615
615:       def id
616:         @values[:id]
617:       end

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

[Source]

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

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

[Source]

     # File lib/sequel/model/base.rb, line 626
626:       def keys
627:         @values.keys
628:       end

Returns true if the current instance represents a new record.

[Source]

     # File lib/sequel/model/base.rb, line 631
631:       def new?
632:         @new
633:       end

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 638
638:       def pk
639:         raise(Error, "No primary key is associated with this model") unless key = primary_key
640:         case key
641:         when Array
642:           key.collect{|k| @values[k]}
643:         else
644:           @values[key]
645:         end
646:       end

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 651
651:       def pk_hash
652:         model.primary_key_hash(pk)
653:       end

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 658
658:       def refresh
659:         @values = this.first || raise(Error, "Record not found")
660:         changed_columns.clear
661:         associations.clear
662:         self
663:       end

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

[Source]

     # File lib/sequel/model/base.rb, line 666
666:       def reload
667:         refresh
668:       end

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
  • :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 683
683:       def save(*columns)
684:         opts = columns.last.is_a?(Hash) ? columns.pop : {}
685:         return save_failure(:invalid) if opts[:validate] != false and !valid?
686:         use_transaction = opts.include?(:transaction) ? opts[:transaction] : use_transactions
687:         use_transaction ? db.transaction(opts){_save(columns, opts)} : _save(columns, opts)
688:       end

[Source]

     # File lib/sequel/model/deprecated.rb, line 136
136:       def save!(*args)
137:         Deprecation.deprecate('Sequel::Model#save!', 'Use model_object.save(..., :validate=>false)')
138:         opts = args.last.is_a?(Hash) ? args.pop : {}
139:         args.push(opts.merge(:validate=>false))
140:         save(*args)
141:       end

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.

[Source]

     # File lib/sequel/model/base.rb, line 693
693:       def save_changes
694:         save(:changed=>true) || false unless changed_columns.empty?
695:       end

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 701
701:       def set(hash)
702:         set_restricted(hash, nil, nil)
703:       end

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 707
707:       def set_all(hash)
708:         set_restricted(hash, false, false)
709:       end

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

[Source]

     # File lib/sequel/model/base.rb, line 713
713:       def set_except(hash, *except)
714:         set_restricted(hash, false, except.flatten)
715:       end

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 719
719:       def set_only(hash, *only)
720:         set_restricted(hash, only.flatten, false)
721:       end

[Source]

     # File lib/sequel/model/deprecated.rb, line 158
158:       def set_values(values)
159:         Deprecation.deprecate('Sequel::Model#set_values', 'Use Sequel::Model#set')
160:         s = str_columns
161:         vals = values.inject({}) do |m, kv|
162:           k, v = kv
163:           k = case k
164:           when Symbol
165:             k
166:           when String
167:             raise(Error, "all string keys must be a valid columns") unless s.include?(k)
168:             k.to_sym
169:           else
170:             raise(Error, "Only symbols and strings allows as keys")
171:           end
172:           m[k] = v
173:           m
174:         end
175:         vals.each {|k, v| @values[k] = v}
176:         vals
177:       end

[Source]

     # File lib/sequel/model/deprecated.rb, line 148
148:       def set_with_params(hash)
149:         Deprecation.deprecate('Sequel::Model#set_with_params', 'Use Sequel::Model#set')
150:         set_restricted(hash, nil, nil)
151:       end

[Source]

     # File lib/sequel/model/deprecated.rb, line 143
143:       def str_columns
144:         Deprecation.deprecate('Sequel::Model#str_columns', 'Use model_object.columns.map{|x| x.to_s}')
145:         model.str_columns
146:       end

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

[Source]

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

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

[Source]

     # File lib/sequel/model/base.rb, line 729
729:       def update(hash)
730:         update_restricted(hash, nil, nil)
731:       end

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 735
735:       def update_all(hash)
736:         update_restricted(hash, false, false)
737:       end

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

[Source]

     # File lib/sequel/model/base.rb, line 741
741:       def update_except(hash, *except)
742:         update_restricted(hash, false, except.flatten)
743:       end

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 747
747:       def update_only(hash, *only)
748:         update_restricted(hash, only.flatten, false)
749:       end

[Source]

     # File lib/sequel/model/deprecated.rb, line 179
179:       def update_values(values)
180:         Deprecation.deprecate('Sequel::Model#update_values', 'Use Sequel::Model#update or model_object.this.update')
181:         this.update(set_values(values))
182:       end

[Source]

     # File lib/sequel/model/deprecated.rb, line 153
153:       def update_with_params(hash)
154:         Deprecation.deprecate('Sequel::Model#update_with_params', 'Use Sequel::Model#update')
155:         update_restricted(hash, nil, nil)
156:       end

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

[Source]

     # File lib/sequel/model/base.rb, line 758
758:       def valid?
759:         errors.clear
760:         if before_validation == false
761:           save_failure(:validation)
762:           return false
763:         end
764:         validate
765:         after_validation
766:         errors.empty?
767:       end

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.

[Source]

     # File lib/sequel/model/base.rb, line 754
754:       def validate
755:       end

[Validate]