Brain  Woodstock
Brain Woodstock

Reputation: 57

How to create unique ID in format xx-123 on rails

is it possible to create some unique ID for articles on rails? For example, first article will get ID - aa-001, second - aa-002 ... article #999 - aa-999, article #1000 - ab-001 and so on?

Thanks in advance for your help!

Upvotes: 1

Views: 198

Answers (2)

Patrick Oscity
Patrick Oscity

Reputation: 54684

You may want to look into the FriendlyId gem. There’s also a Railscast on this topic which covers a manual approach as well as the usage of FriendlyId.

Upvotes: 1

Sirupsen
Sirupsen

Reputation: 2115

The following method gives the next id in the sequence, given the one before:

def next_id(id, limit = 3, seperator = '-')
  if id[/[0-9]+\z/] == ?9 * limit
    "#{id[/\A[a-z]+/i].next}#{seperator}#{?0 * (limit - 1)}1"
  else
    id.next
  end
end

> next_id("aa-009")
=> "aa-010"
> next_id("aa-999")
=> "ab-001"

The limit parameter specifies the number of digits. You can use as many prefix characters as you want.

Which means you could use it like this in your application:

> Post.last.special_id
=> "bc-999"
next_id(Post.last.special_id)
=> "bd-001"

However, I'm not sure I'd advice you to do it like this. Databases have smart methods to avoid race conditions for creating ids when entries are created concurrently. In Postgres, for example, it doesn't guarantee gapless ids.

This approach has no such mechanism, which could potentially lead to race conditions. However, if this is extremely unlikely to happen such in a case where you are the only one writing articles, you could do it anyway. I'm not exactly sure what you want to use this for, but you might want to look into to_param.

Upvotes: 2

Related Questions