Files

Class Index [+]

Quicksearch

ActiveRecord::Persistence

Active Record Persistence

Public Instance Methods

becomes(klass) click to toggle source

Returns an instance of the specified klass with the attributes of the current record. This is mostly useful in relation to single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record identification in Action Pack to allow, say, Client < Company to do something like render :partial => @client.becomes(Company) to render that instance using the companies/company partial instead of clients/client.

Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either instance will affect the other.

     # File lib/active_record/persistence.rb, line 158
158:     def becomes(klass)
159:       became = klass.new
160:       became.instance_variable_set("@attributes", @attributes)
161:       became.instance_variable_set("@attributes_cache", @attributes_cache)
162:       became.instance_variable_set("@new_record", new_record?)
163:       became.instance_variable_set("@destroyed", destroyed?)
164:       became.instance_variable_set("@errors", errors)
165:       became.type = klass.name unless self.class.descends_from_active_record?
166:       became
167:     end
decrement(attribute, by = 1) click to toggle source

Initializes attribute to zero if nil and subtracts the value passed as by (default is 1). The decrement is performed directly on the underlying attribute, no setter is invoked. Only makes sense for number-based attributes. Returns self.

     # File lib/active_record/persistence.rb, line 252
252:     def decrement(attribute, by = 1)
253:       self[attribute] ||= 0
254:       self[attribute] -= by
255:       self
256:     end
decrement!(attribute, by = 1) click to toggle source

Wrapper around decrement that saves the record. This method differs from its non-bang version in that it passes through the attribute setter. Saving is not subjected to validation checks. Returns true if the record could be saved.

     # File lib/active_record/persistence.rb, line 262
262:     def decrement!(attribute, by = 1)
263:       decrement(attribute, by).update_column(attribute, self[attribute])
264:     end
delete() click to toggle source

Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted). Returns the frozen instance.

The row is simply removed with an SQL DELETE statement on the record’s primary key, and no callbacks are executed.

To enforce the object’s before_destroy and after_destroy callbacks, Observer methods, or any :dependent association options, use #.

     # File lib/active_record/persistence.rb, line 117
117:     def delete
118:       if persisted?
119:         self.class.delete(id)
120:         IdentityMap.remove(self) if IdentityMap.enabled?
121:       end
122:       @destroyed = true
123:       freeze
124:     end
destroy() click to toggle source

Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted).

     # File lib/active_record/persistence.rb, line 128
128:     def destroy
129:       destroy_associations
130: 
131:       if persisted?
132:         IdentityMap.remove(self) if IdentityMap.enabled?
133:         pk         = self.class.primary_key
134:         column     = self.class.columns_hash[pk]
135:         substitute = connection.substitute_at(column, 0)
136: 
137:         relation = self.class.unscoped.where(
138:           self.class.arel_table[pk].eq(substitute))
139: 
140:         relation.bind_values = [[column, id]]
141:         relation.delete_all
142:       end
143: 
144:       @destroyed = true
145:       freeze
146:     end
destroyed?() click to toggle source

Returns true if this object has been destroyed, otherwise returns false.

    # File lib/active_record/persistence.rb, line 58
58:     def destroyed?
59:       @destroyed
60:     end
increment(attribute, by = 1) click to toggle source

Initializes attribute to zero if nil and adds the value passed as by (default is 1). The increment is performed directly on the underlying attribute, no setter is invoked. Only makes sense for number-based attributes. Returns self.

     # File lib/active_record/persistence.rb, line 235
235:     def increment(attribute, by = 1)
236:       self[attribute] ||= 0
237:       self[attribute] += by
238:       self
239:     end
increment!(attribute, by = 1) click to toggle source

Wrapper around increment that saves the record. This method differs from its non-bang version in that it passes through the attribute setter. Saving is not subjected to validation checks. Returns true if the record could be saved.

     # File lib/active_record/persistence.rb, line 245
245:     def increment!(attribute, by = 1)
246:       increment(attribute, by).update_column(attribute, self[attribute])
247:     end
new_record?() click to toggle source

Returns true if this object hasn’t been saved yet — that is, a record for the object doesn’t exist in the data store yet; otherwise, returns false.

    # File lib/active_record/persistence.rb, line 53
53:     def new_record?
54:       @new_record
55:     end
persisted?() click to toggle source

Returns if the record is persisted, i.e. it’s not a new record and it was not destroyed.

    # File lib/active_record/persistence.rb, line 64
64:     def persisted?
65:       !(new_record? || destroyed?)
66:     end
reload(options = nil) click to toggle source

Reloads the attributes of this object from the database. The optional options argument is passed to find when reloading so you may do e.g. record.reload(:lock => true) to reload the same record with an exclusive row lock.

     # File lib/active_record/persistence.rb, line 287
287:     def reload(options = nil)
288:       clear_aggregation_cache
289:       clear_association_cache
290: 
291:       IdentityMap.without do
292:         fresh_object = self.class.unscoped { self.class.find(self.id, options) }
293:         @attributes.update(fresh_object.instance_variable_get('@attributes'))
294:       end
295: 
296:       @attributes_cache = {}
297:       self
298:     end
save(*) click to toggle source

Saves the model.

If the model is new a record gets created in the database, otherwise the existing record gets updated.

By default, save always run validations. If any of them fail the action is cancelled and save returns false. However, if you supply :validate => false, validations are bypassed altogether. See ActiveRecord::Validations for more information.

There’s a series of callbacks associated with save. If any of the before_* callbacks return false the action is cancelled and save returns false. See ActiveRecord::Callbacks for further details.

    # File lib/active_record/persistence.rb, line 82
82:     def save(*)
83:       begin
84:         create_or_update
85:       rescue ActiveRecord::RecordInvalid
86:         false
87:       end
88:     end
save!(*) click to toggle source

Saves the model.

If the model is new a record gets created in the database, otherwise the existing record gets updated.

With save! validations always run. If any of them fail ActiveRecord::RecordInvalid gets raised. See ActiveRecord::Validations for more information.

There’s a series of callbacks associated with save!. If any of the before_* callbacks return false the action is cancelled and save! raises ActiveRecord::RecordNotSaved. See ActiveRecord::Callbacks for further details.

     # File lib/active_record/persistence.rb, line 103
103:     def save!(*)
104:       create_or_update || raise(RecordNotSaved)
105:     end
toggle(attribute) click to toggle source

Assigns to attribute the boolean opposite of attribute?. So if the predicate returns true the attribute will become false. This method toggles directly the underlying value without calling any setter. Returns self.

     # File lib/active_record/persistence.rb, line 270
270:     def toggle(attribute)
271:       self[attribute] = !send("#{attribute}?")
272:       self
273:     end
toggle!(attribute) click to toggle source

Wrapper around toggle that saves the record. This method differs from its non-bang version in that it passes through the attribute setter. Saving is not subjected to validation checks. Returns true if the record could be saved.

     # File lib/active_record/persistence.rb, line 279
279:     def toggle!(attribute)
280:       toggle(attribute).update_column(attribute, self[attribute])
281:     end
touch(name = nil) click to toggle source

Saves the record with the updated_at/on attributes set to the current time. Please note that no validation is performed and no callbacks are executed. If an attribute name is passed, that attribute is updated along with updated_at/on attributes.

  product.touch               # updates updated_at/on
  product.touch(:designed_at) # updates the designed_at attribute and updated_at/on

If used along with belongs_to then touch will invoke touch method on associated object.

  class Brake < ActiveRecord::Base
    belongs_to :car, :touch => true
  end

  class Car < ActiveRecord::Base
    belongs_to :corporation, :touch => true
  end

  # triggers @brake.car.touch and @brake.car.corporation.touch
  @brake.touch
     # File lib/active_record/persistence.rb, line 320
320:     def touch(name = nil)
321:       attributes = timestamp_attributes_for_update_in_model
322:       attributes << name if name
323: 
324:       unless attributes.empty?
325:         current_time = current_time_from_proper_timezone
326:         changes = {}
327: 
328:         attributes.each do |column|
329:           changes[column.to_s] = write_attribute(column.to_s, current_time)
330:         end
331: 
332:         changes[self.class.locking_column] = increment_lock if locking_enabled?
333: 
334:         @changed_attributes.except!(*changes.keys)
335:         primary_key = self.class.primary_key
336:         self.class.unscoped.update_all(changes, { primary_key => self[primary_key] }) == 1
337:       end
338:     end
update_attribute(name, value) click to toggle source

Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records. Also note that

  • Validation is skipped.

  • Callbacks are invoked.

  • updated_at/updated_on column is updated if that column is available.

  • Updates all the attributes that are dirty in this object.

This method has been deprecated in favor of update_column due to its similarity with update_attributes.

     # File lib/active_record/persistence.rb, line 180
180:     def update_attribute(name, value)
181:       name = name.to_s
182:       ActiveSupport::Deprecation.warn("update_attribute is deprecated and will be removed in Rails 4. If you want to skip mass-assignment protection, callbacks, and modifying updated_at, use update_column. If you do want those things, use update_attributes.")
183:       raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
184:       send("#{name}=", value)
185:       save(:validate => false)
186:     end
update_attributes(attributes, options = {}) click to toggle source

Updates the attributes of the model from the passed-in hash and saves the record, all wrapped in a transaction. If the object is invalid, the saving will fail and false will be returned.

When updating model attributes, mass-assignment security protection is respected. If no :as option is supplied then the :default role will be used. If you want to bypass the protection given by attr_protected and attr_accessible then you can do so using the :without_protection option.

     # File lib/active_record/persistence.rb, line 212
212:     def update_attributes(attributes, options = {})
213:       # The following transaction covers any possible database side-effects of the
214:       # attributes assignment. For example, setting the IDs of a child collection.
215:       with_transaction_returning_status do
216:         self.assign_attributes(attributes, options)
217:         save
218:       end
219:     end
update_attributes!(attributes, options = {}) click to toggle source

Updates its receiver just like update_attributes but calls save! instead of save, so an exception is raised if the record is invalid.

     # File lib/active_record/persistence.rb, line 223
223:     def update_attributes!(attributes, options = {})
224:       # The following transaction covers any possible database side-effects of the
225:       # attributes assignment. For example, setting the IDs of a child collection.
226:       with_transaction_returning_status do
227:         self.assign_attributes(attributes, options)
228:         save!
229:       end
230:     end
update_column(name, value) click to toggle source

Updates a single attribute of an object, without calling save.

  • Validation is skipped.

  • Callbacks are skipped.

  • updated_at/updated_on column is not updated if that column is available.

Raises an ActiveRecordError when called on new objects, or when the name attribute is marked as readonly.

     # File lib/active_record/persistence.rb, line 196
196:     def update_column(name, value)
197:       name = name.to_s
198:       raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
199:       raise ActiveRecordError, "can not update on a new record object" unless persisted?
200:       raw_write_attribute(name, value)
201:       self.class.update_all({ name => value }, self.class.primary_key => id) == 1
202:     end

Private Instance Methods

create() click to toggle source

Creates a record with values matching those of the instance attributes and returns its id.

     # File lib/active_record/persistence.rb, line 364
364:     def create
365:       attributes_values = arel_attributes_values(!id.nil?)
366: 
367:       new_id = self.class.unscoped.insert attributes_values
368: 
369:       self.id ||= new_id if self.class.primary_key
370: 
371:       IdentityMap.add(self) if IdentityMap.enabled?
372:       @new_record = false
373:       id
374:     end
create_or_update() click to toggle source
     # File lib/active_record/persistence.rb, line 346
346:     def create_or_update
347:       raise ReadOnlyRecord if readonly?
348:       result = new_record? ? create : update
349:       result != false
350:     end
destroy_associations() click to toggle source

A hook to be overridden by association modules.

     # File lib/active_record/persistence.rb, line 343
343:     def destroy_associations
344:     end
update(attribute_names = @attributes.keys) click to toggle source

Updates the associated record with values matching those of the instance attributes. Returns the number of affected rows.

     # File lib/active_record/persistence.rb, line 354
354:     def update(attribute_names = @attributes.keys)
355:       attributes_with_values = arel_attributes_values(false, false, attribute_names)
356:       return 0 if attributes_with_values.empty?
357:       klass = self.class
358:       stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values)
359:       klass.connection.update stmt
360:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.