I’m creating a Rails app that communicates with an old SQL database and I need to set the primary_key.
Intially I did this:
class Post < ActiveRecord::Base
attr_accessible :body, :title, :incrementer_id
self.primary_key = "incrementer_id"
before_create :next_seq, on: :create
private
def next_seq
p = Post.last
self.incrementer_id = p.blank? ? 1 : (p.incrementer_id.to_i + 1)
end
end
I needed to create the next_seq because Rails doesn’t automatically increase the ‘incrementer_id’.
I had to make the ternary because the first item’s incrementer_id is nil and it was giving error. I would love to avoid having to make this check every time.
I wonder if there’s an optimal way to do the next_seq. Even better, make it database-type independent.
First of all, I wouldn’t count on the
Post.lastmethod to give you the item with the highest numbered ID. For that, you wouldPost.maximum(:id). In Ruby, since&&and||work with any kinds of values, not just booleans, andnilis treated as falsey, you can say…Doing this involves an extra round trip to the database for every save, and finding the maximum existing ID might not be terribly efficient. If you write a lot of these records, you might consider using a pool of IDs in memory. To do that, you need a row in another table that stores the next available ID, and the first time your app needs a new one, increment that by some value such as 10 or 100, in effect reserving that many IDs for use by your application instance. Assign ID values from that range until it is used up, and then acquire a new pool of IDs as before.
If you use the pooling strategy and the database is shared by another app that computes new IDs by adding 1 to the maximum existing ID, you can make your strategy compatible with that by assigning IDs in descending order from the pool.