incremental counter in DB

I have an application that sends messages and each message that gets sent needs to have a unique sequence number, this sequence number is incremented with each message. As I understand it, I should be storing this sequence number in the DB rather than in a global variable.

My question is, how do I use rails and active record to define this table? The table doesn't need to have any of the active record things like an auto incrementing integer ID, it justs needs to be a single column, single row table storing an integer value that I can easily increment.

Why not just do the following in your Message model:

before_save :assign_sequence_number

protected

def assign_sequence_number

last_number = self.class.maximum(‘sequence_number’, :conditions => [])

if last_number.nil?

self.sequence_number = 1

else

self.sequence_number = last_number+1

end

end

Best regards

Peter De Berdt

I did think of finding the maximum of all the sequence numbers in the table and then incrementing it, I just thought that it'd be quicker (as the message table grows large) to grab the number from a separate table which only stores the last number used. I'll implement it using your method for now, I can always revisit it if there is a performance concern. thanks for the help

You can also implement a Preference model. I tend to favour a multirecord preference table, where each record signifies one particular preference, in your case this preference will be current_counter_value which is an integer. I tend to mask this Preference model behind a few convenience methods, similar as to what the restful_authentication plugin does with the current_user method, i.e. providing you with a method like “counter_number”, which automatically returns the current counter and increases the preference counter by one.

You could check out the settings plugin at http://beautifulpixel.com/2006/02/25/settings-plugin, although i haven’t used it myself.

Best regards

Peter De Berdt

single row table makes no sense why not create Message model, backed with messages table, having all those activerecord things, like id (which is in fact unique sequence number), and other message attributes?