Module: ActiveRecord::Base::CompositeInstanceMethods

Defined in:
lib/composite_primary_keys/base.rb

Instance Method Summary collapse

Instance Method Details

#can_change_primary_key_values?Boolean

Returns:

  • (Boolean)


126
127
128
# File 'lib/composite_primary_keys/base.rb', line 126

def can_change_primary_key_values?
  false
end

#idObject Also known as: ids

A model instance’s primary keys is always available as model.ids whether you name it the default ‘id’ or set it to something else.



86
87
88
89
# File 'lib/composite_primary_keys/base.rb', line 86

def id
  attr_names = self.class.primary_keys
  ::CompositePrimaryKeys::CompositeKeys.new(attr_names.map { |attr_name| read_attribute(attr_name) })
end

#id=(ids) ⇒ Object

Sets the primary ID.



117
118
119
120
121
122
123
124
# File 'lib/composite_primary_keys/base.rb', line 117

def id=(ids)
  ids = CompositePrimaryKeys::CompositeKeys.parse(ids)
  unless ids.length == self.class.primary_keys.length
    raise "#{self.class}.id= requires #{self.class.primary_keys.length} ids"
  end
  [self.class.primary_keys, ids].transpose.each {|key, an_id| write_attribute(key , an_id)}
  id
end

#id_before_type_castObject



110
111
112
113
114
# File 'lib/composite_primary_keys/base.rb', line 110

def id_before_type_cast
  self.class.primary_keys.map do |key|
    self.read_attribute_before_type_cast(key)
  end
end

#ids_hashObject



103
104
105
106
107
108
# File 'lib/composite_primary_keys/base.rb', line 103

def ids_hash
  self.class.primary_key.zip(ids).inject(Hash.new) do |hash, (key, value)|
    hash[key] = value
    hash
  end
end

#read_attribute_for_serialization(attribute) ⇒ Object

This is overridden purely for json serialization support. If the model is composite and one of the keys is id, then we don’t want to call the id method, instead we want to get the id attribute value



95
96
97
98
99
100
101
# File 'lib/composite_primary_keys/base.rb', line 95

def read_attribute_for_serialization(attribute)
  if self.composite? && attribute == 'id'
    read_attribute(attribute)
  else
    send(attribute)
  end
end

#to_keyObject

Returns this record’s primary keys values in an Array if any value is available



132
133
134
# File 'lib/composite_primary_keys/base.rb', line 132

def to_key
  ids.to_a if !ids.compact.empty? # XXX Maybe use primary_keys with send instead of ids
end