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)


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

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.



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

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.



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

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



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

def id_before_type_cast
  self.class.primary_keys.map do |key|
    self.send("#{key.to_s}_before_type_cast")
  end
end

#ids_hashObject



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

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



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

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

#to_paramObject



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

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