Module: ActiveRecord::Base::CompositeInstanceMethods
- Defined in:
- lib/composite_primary_keys/base.rb
Instance Method Summary collapse
- #==(comparison_object) ⇒ Object
- #can_change_primary_key_values? ⇒ Boolean
-
#id ⇒ Object
(also: #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.
-
#id=(ids) ⇒ Object
Sets the primary ID.
- #id_before_type_cast ⇒ Object
- #ids_hash ⇒ Object
-
#to_key ⇒ Object
Returns this record’s primary keys values in an Array if any value is available.
Instance Method Details
#==(comparison_object) ⇒ Object
138 139 140 |
# File 'lib/composite_primary_keys/base.rb', line 138 def ==(comparison_object) ids.is_a?(Array) ? super(comparison_object) && ids.all? {|id| id.present?} : super(comparison_object) end |
#can_change_primary_key_values? ⇒ Boolean
142 143 144 |
# File 'lib/composite_primary_keys/base.rb', line 142 def can_change_primary_key_values? false end |
#id ⇒ Object 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.
108 109 110 111 |
# File 'lib/composite_primary_keys/base.rb', line 108 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.
128 129 130 131 132 133 134 135 136 |
# File 'lib/composite_primary_keys/base.rb', line 128 def id=(ids) ids = ids.split(CompositePrimaryKeys::ID_SEP) if ids.is_a?(String) ids.flatten! unless ids.is_a?(Array) and 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_cast ⇒ Object
121 122 123 124 125 |
# File 'lib/composite_primary_keys/base.rb', line 121 def id_before_type_cast self.class.primary_keys.map do |key| self.send("#{key.to_s}_before_type_cast") end end |
#ids_hash ⇒ Object
114 115 116 117 118 119 |
# File 'lib/composite_primary_keys/base.rb', line 114 def ids_hash self.class.primary_key.zip(ids).inject(Hash.new) do |hash, (key, value)| hash[key] = value hash end end |
#to_key ⇒ Object
Returns this record’s primary keys values in an Array if any value is available
148 149 150 |
# File 'lib/composite_primary_keys/base.rb', line 148 def to_key ids.to_a if !ids.compact.empty? # XXX Maybe use primary_keys with send instead of ids end |