Module: UpdateCardinalsBy
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/update_cardinals_by.rb,
lib/update_cardinals_by/version.rb
Constant Summary collapse
- VERSION =
"0.2.0"
Instance Method Summary collapse
-
#update_cardinals_by!(attributes, &block) ⇒ Object
Changes given attributes by delta.
Instance Method Details
#update_cardinals_by!(attributes, &block) ⇒ Object
Changes given attributes by delta.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/update_cardinals_by.rb', line 11 def update_cardinals_by!(attributes, &block) db_attributes = attributes.map { |k, v| [self.class.connection.quote_column_name(k), v] } updates = db_attributes.map.with_index { |(k, v), i| "#{k} = #{k} + $#{i+1}" } binds = attributes.map { |k, v| [column_for_attribute(k), v] } transaction do res = self.class.connection.exec_query( "update #{self.class.table_name} " \ "set #{updates.join(', ')} " \ "where id = #{id} " \ "returning #{db_attributes.map(&:first).join(', ')}", 'SQL', binds ).first .map { |k, v| [k, type_for_attribute(k).cast(v)] } res = HashWithIndifferentAccess[ res ] yield res if block_given? res.each do |attr, v| write_attribute attr, v clear_attribute_change attr end end end |