Skip to content

Instantly share code, notes, and snippets.

@biscuitvile
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save biscuitvile/43e08866bac6dd9b57d4 to your computer and use it in GitHub Desktop.

Select an option

Save biscuitvile/43e08866bac6dd9b57d4 to your computer and use it in GitHub Desktop.
Increment all attributes in a relation with two queries using ActiveRecord increment_counter and pluck methods
class Product < ActiveRecord::Base
# we could use the below version to acheive
# the desired result in a single statement
# with raw sql, however this solution
# wouldn't be database agnostic and I think
# most developers would prefer the ruby
# version as two queries is still very
# fast.
#
# def self.increment_positions
# connection.execute("UPDATE products SET position = position + 1")
# end
#
# Additionally, this will update all rows
# in the products table and connot be scoped.
# The below version can.
def self.increment_positions
increment_counter :position, pluck(:id)
end
end
describe ".increment_positions" do
it 'increments all positions in a relation' do
a, b = create(:product, position: 1), create(:product, position: 2)
Product.increment_positions
a.reload.position.must_equal 2
b.reload.position.must_equal 3
end
it 'does not increment positions outside a relation' do
a, b = create(:product, position: 1), create(:product, position: 2)
Product.where.not(position: 1).increment_positions
a.reload.position.must_equal 1
b.reload.position.must_equal 3
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment