Module: ReloadAttribute::InstanceMethods

Defined in:
lib/reload_attribute/instance_methods.rb

Overview

Methods added to all ActiveRecord models

Instance Method Summary collapse

Instance Method Details

#reload_attribute(*attrs) ⇒ Hash? Also known as: reload_attributes

Updates the models supplied attributes from the database.

Parameters:

  • attrs (String)

    the attributes to reload

Returns:

  • (Hash)

    the attributes that were reloaded

  • (nil)

    if the model is not persisted



11
12
13
14
15
16
17
18
19
# File 'lib/reload_attribute/instance_methods.rb', line 11

def reload_attribute(*attrs)
  return if new_record?
  values = self.class.where(id: id).select(attrs.join(', ')).first.slice(*attrs)
  values.each_with_object({}) do |attr, memo|
    name, value = attr
    self[name] = memo[name] = value
    memo
  end
end