class Buyer < ActiveRecord::Base
scope :positioned_at_or_above, lambda {|pos| where("position >= ?", pos) }
def self.increment(amount, position_threshold)
Buyer.positioned_at_or_above(position_threshold).each{|buyer| buyer.update_attributes(:position => buyer.position + amount)}
end
end
-
increment ∴ rails c
Loading development environment (Rails 3.0.3)
>> Buyer.count
=> 0
>> (1..10).each {|idx| Buyer.create(:name => "Buyer ##{idx}", :position => idx)}
=> 1..10
>> pp Buyer.all
[#<Buyer id: 11, name: "Buyer #1", position: 1>,
#<Buyer id: 12, name: "Buyer #2", position: 2>,
#<Buyer id: 13, name: "Buyer #3", position: 3>,
#<Buyer id: 14, name: "Buyer #4", position: 4>,
#<Buyer id: 15, name: "Buyer #5", position: 5>,
#<Buyer id: 16, name: "Buyer #6", position: 6>,
#<Buyer id: 17, name: "Buyer #7", position: 7>,
#<Buyer id: 18, name: "Buyer #8", position: 8>,
#<Buyer id: 19, name: "Buyer #9", position: 9>,
#<Buyer id: 20, name: "Buyer #10", position: 10>]
=> nil
>> pp Buyer.positioned_at_or_above(4)
[#<Buyer id: 14, name: "Buyer #4", position: 4>, #<Buyer id: 15, name: "Buyer #5", position: 5>, #<Buyer id: 16, name: "Buyer #6", position: 6>, #<Buyer id: 17, name: "Buyer #7", position: 7>, #<Buyer id: 18, name: "Buyer #8", position: 8>, #<Buyer id: 19, name: "Buyer #9", position: 9>, #<Buyer id: 20, name: "Buyer #10", position: 10>]
=> nil
>> pp Buyer.positioned_at_or_above(4).all
[#<Buyer id: 14, name: "Buyer #4", position: 4>,
#<Buyer id: 15, name: "Buyer #5", position: 5>,
#<Buyer id: 16, name: "Buyer #6", position: 6>,
#<Buyer id: 17, name: "Buyer #7", position: 7>,
#<Buyer id: 18, name: "Buyer #8", position: 8>,
#<Buyer id: 19, name: "Buyer #9", position: 9>,
#<Buyer id: 20, name: "Buyer #10", position: 10>]
=> nil
>> Buyer.increment(1000, 4)
=> [#<Buyer id: 14, name: "Buyer #4", position: 1004>, #<Buyer id: 15, name: "Buyer #5", position: 1005>, #<Buyer id: 16, name: "Buyer #6", position: 1006>, #<Buyer id: 17, name: "Buyer #7", position: 1007>, #<Buyer id: 18, name: "Buyer #8", position: 1008>, #<Buyer id: 19, name: "Buyer #9", position: 1009>, #<Buyer id: 20, name: "Buyer #10", position: 1010>]
>> pp Buyer.all
[#<Buyer id: 11, name: "Buyer #1", position: 1>,
#<Buyer id: 12, name: "Buyer #2", position: 2>,
#<Buyer id: 13, name: "Buyer #3", position: 3>,
#<Buyer id: 14, name: "Buyer #4", position: 1004>,
#<Buyer id: 15, name: "Buyer #5", position: 1005>,
#<Buyer id: 16, name: "Buyer #6", position: 1006>,
#<Buyer id: 17, name: "Buyer #7", position: 1007>,
#<Buyer id: 18, name: "Buyer #8", position: 1008>,
#<Buyer id: 19, name: "Buyer #9", position: 1009>,
#<Buyer id: 20, name: "Buyer #10", position: 1010>]
=> nil
>>
¿En la consola o un método en la aplicación? ¿Es esto una solución única? –
como método en la aplicación –