Module: Sequel::Model::InstanceMethods

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

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.



469
470
471
# File 'lib/sequel/model/base.rb', line 469

def values
  @values
end

Instance Method Details

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

Compares model instances by values.



515
516
517
# File 'lib/sequel/model/base.rb', line 515

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.



522
523
524
# File 'lib/sequel/model/base.rb', line 522

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

#[](column) ⇒ Object

Returns value of the column’s attribute.



497
498
499
# File 'lib/sequel/model/base.rb', line 497

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.



503
504
505
506
507
508
509
510
511
512
# File 'lib/sequel/model/base.rb', line 503

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



535
536
537
# File 'lib/sequel/model/base.rb', line 535

def associations
  @associations ||= {}
end

#changed_columnsObject

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



541
542
543
# File 'lib/sequel/model/base.rb', line 541

def changed_columns
  @changed_columns ||= []
end

#datasetObject



117
118
119
120
# File 'lib/sequel/model/deprecated.rb', line 117

def dataset
  Deprecation.deprecate('Sequel::Model#dataset', 'Use model_object.model.dataset')
  model.dataset
end

#deleteObject

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



547
548
549
550
# File 'lib/sequel/model/base.rb', line 547

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.



556
557
558
# File 'lib/sequel/model/base.rb', line 556

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

#each(&block) ⇒ Object

Enumerates through all attributes.

Example:

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


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

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

#errorsObject

Returns the validation errors associated with the object.



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

def errors
  @errors ||= Errors.new
end

#exists?Boolean

Returns true when current instance exists, false otherwise.

Returns:

  • (Boolean)


574
575
576
# File 'lib/sequel/model/base.rb', line 574

def exists?
  this.count > 0
end

#hashObject

Unique for objects with the same class and pk (if pk is not nil), or the same class and values (if pk is nil).



580
581
582
# File 'lib/sequel/model/base.rb', line 580

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.



586
587
588
# File 'lib/sequel/model/base.rb', line 586

def id
  @values[:id]
end

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

Creates new instance with values set to passed-in Hash. 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 with symbol keys, though string keys will work if from_db is false.

  • from_db - should only be set by Model.load, forget it exists.



482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'lib/sequel/model/base.rb', line 482

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.



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

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

#keysObject

Returns attribute names as an array of symbols.



597
598
599
# File 'lib/sequel/model/base.rb', line 597

def keys
  @values.keys
end

#new?Boolean

Returns true if the current instance represents a new record.

Returns:

  • (Boolean)


602
603
604
# File 'lib/sequel/model/base.rb', line 602

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:



609
610
611
612
613
614
615
616
617
# File 'lib/sequel/model/base.rb', line 609

def pk
  raise(Error, "No primary key is associated with this model") unless key = primary_key
  case key
  when Array
    key.collect{|k| @values[k]}
  else
    @values[key]
  end
end

#pk_hashObject

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

Model[model_instance.pk_hash] === model_instance


622
623
624
# File 'lib/sequel/model/base.rb', line 622

def pk_hash
  model.primary_key_hash(pk)
end

#refreshObject Also known as: reload

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



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

def refresh
  @values = this.first || raise(Error, "Record not found")
  changed_columns.clear
  associations.clear
  self
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

  • :transaction - set to false not to use a transaction

  • :validate - set to false not to validate the model before saving



650
651
652
653
654
655
656
657
658
659
# File 'lib/sequel/model/base.rb', line 650

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

#save!(*args) ⇒ Object



122
123
124
125
126
127
# File 'lib/sequel/model/deprecated.rb', line 122

def save!(*args)
  Deprecation.deprecate('Sequel::Model#save!', 'Use model_object.save(..., :validate=>false)')
  opts = args.last.is_a?(Hash) ? args.pop : {}
  args.push(opts.merge(:validate=>false))
  save(*args)
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.



664
665
666
# File 'lib/sequel/model/base.rb', line 664

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.

If no columns have been set for this model (very unlikely), assume symbol keys are valid column names, and assign the column value based on that.



675
676
677
# File 'lib/sequel/model/base.rb', line 675

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.



681
682
683
# File 'lib/sequel/model/base.rb', line 681

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.



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

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.



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

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

#set_values(values) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/sequel/model/deprecated.rb', line 144

def set_values(values)
  Deprecation.deprecate('Sequel::Model#set_values', 'Use Sequel::Model#set')
  s = str_columns
  vals = values.inject({}) do |m, kv|
    k, v = kv
    k = case k
    when Symbol
      k
    when String
      raise(Error, "all string keys must be a valid columns") unless s.include?(k)
      k.to_sym
    else
      raise(Error, "Only symbols and strings allows as keys")
    end
    m[k] = v
    m
  end
  vals.each {|k, v| @values[k] = v}
  vals
end

#set_with_params(hash) ⇒ Object



134
135
136
137
# File 'lib/sequel/model/deprecated.rb', line 134

def set_with_params(hash)
  Deprecation.deprecate('Sequel::Model#set_with_params', 'Use Sequel::Model#set')
  set_restricted(hash, nil, nil)
end

#str_columnsObject



129
130
131
132
# File 'lib/sequel/model/deprecated.rb', line 129

def str_columns
  Deprecation.deprecate('Sequel::Model#str_columns', 'Use model_object.columns.map{|x| x.to_s}')
  model.str_columns
end

#thisObject

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



698
699
700
# File 'lib/sequel/model/base.rb', line 698

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



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

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.



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

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.



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

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.



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

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

#update_values(values) ⇒ Object



165
166
167
168
# File 'lib/sequel/model/deprecated.rb', line 165

def update_values(values)
  Deprecation.deprecate('Sequel::Model#update_values', 'Use Sequel::Model#update or model_object.this.update')
  this.update(set_values(values))
end

#update_with_params(hash) ⇒ Object



139
140
141
142
# File 'lib/sequel/model/deprecated.rb', line 139

def update_with_params(hash)
  Deprecation.deprecate('Sequel::Model#update_with_params', 'Use Sequel::Model#update')
  update_restricted(hash, nil, nil)
end

#valid?Boolean

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

Returns:

  • (Boolean)


732
733
734
735
736
737
738
739
740
741
# File 'lib/sequel/model/base.rb', line 732

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.



728
729
# File 'lib/sequel/model/base.rb', line 728

def validate
end