Trip
Trip

Reputation: 27114

Writing a simple incrementing counter in rails

For every Card, I would like to attach a special number to them that increments by one.

I assume I can do this all in the controller.

def create
 @card = Card.new(params[:card])
 @card.SpecNum = @card.SpecNum ++
...
end

Or. I can be blatantly retarded. And maybe the best bet is to add an auto-incremement table to mysql. The problem is the number has to start at a specific number, 1020.

Any ideas?

Upvotes: 0

Views: 1080

Answers (2)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

Personally, I wouldn't put that responsibility on the database, or the controller; I like it in the model. Something like:

/app/models/card

validates_uniqueness_of :special_number

def before_validation_on_create
  self.special_number = CardSpecialNumber.next!
end

/app/models/card_special_number

def self.next!
  last_number_holder = CardSpecialNumber.first
  if last_number_holder.nil?
    CardSpecialNumber.create!(:counter => 1020)
    return 1020
  end

  last_number_holder.counter = last_number_holder.counter + 1
  last_number_holder.save!
  last_number_holder.counter
end

Upvotes: 1

OMG Ponies
OMG Ponies

Reputation: 332521

You can set (and reset) MySQL's AUTO_INCREMENT value on a per table basis using an ALTER TABLE statement:

ALTER TABLE mytable AUTO_INCREMENT = 1020

ALTER TABLE is not a privilege you want all users to have, see about securing it appropriately.

Upvotes: 2

Related Questions