Carpetfizz
Carpetfizz

Reputation: 9149

Stronger Active Record IDs

How can we get Active Record to create more complex IDs that are not just the natural numbers (1, 2, 3 ...). I'm not sure if I should be using database IDs to identify objects, but I am now and it would be pretty insecure to have them like this in production.

Upvotes: 0

Views: 45

Answers (1)

Amree
Amree

Reputation: 2890

Lets just say you want to use a column called slug for an object called Post.

  • Create a slug column for that table
  • Create a before_create method in Post model that will generate a unique slug value before saving the record. Maybe do some checking to ensure it’s unique
  • Replace anything that’s public facing to use Post.find_by(slug: id) instead of Post.find(id).
  • Ensure any url generation will use something like this: post_path(id: post.slug) so that it won't put the id the URL.

Upvotes: 1

Related Questions