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)


115
116
117
# File 'lib/composite_primary_keys/base.rb', line 115

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.



106
107
108
109
110
111
112
113
# File 'lib/composite_primary_keys/base.rb', line 106

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



99
100
101
102
103
# File 'lib/composite_primary_keys/base.rb', line 99

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

#ids_hashObject



92
93
94
95
96
97
# File 'lib/composite_primary_keys/base.rb', line 92

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

#to_keyObject

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



121
122
123
# File 'lib/composite_primary_keys/base.rb', line 121

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

#to_paramObject



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

def to_param
  persisted? ? to_key.join(CompositePrimaryKeys::ID_SEP) : nil
end