ruby on rails - Better, non numerical and non sequencial ids for ActiveRecord -


I use ActiveRecord in my Rail 4.1.1 application and I keep the objects in the database but I actually I do not like the IDs assigned to my objects (1, 2, 3, and so on) I want these IDs to be non-integer and non-sequential, such as mongoide gem.

How can I do this?

I assume that you want this change because you do not like how id The URL is coming ...

http://my_application.com/posts/3.html

There is no other reason to change the ID. .. They do things that they want and they are internal to the app (except for the above situation).

The technique you can think of is using the "slug"

Create an attribute in your model called Slug , which will be used by your model " Title "or" name ", but in a URL-friendly format ... make it an earlier action ...

  class post  ActiveRecord :: before bbs_service: create_slug def create_slug #strip string slug = title. Streft # Blowlo Apostrops slug.gsub! / ['`] /," "# @ - & gt; On, and & amp; - & gt; And slug.gsub! / \ S * @ \ s * /, "at" slug.gsub! / \ S * and / s * /, "and" #replace All non-alphanumeric, underscore or underscore slug.gsub! / Ss * [^ A-Za-z0-9 ASASN, '_' # Convert Double Underscores for Single Slug.gsub! / _ + /, "_" #strip leading / trailing underscore slug.gsub! />A[_\.]+|[_\.]+\z/, "#" Make sure the slug is unique ... unique = false appendix = "counter = 0" unique test_slug = slug + appendix test_object = Self.class.find_by_slug (test_slug) unique = true until test_object & amp; test_object! = Self counter + = 1 appendix = "_ # {counter}" end self.slug = test_slug end end  

Then create a 'to_param' method in your class ... This will create the "User_friendly" id which will appear in the URL

  def to_param slug end  

Finally, you need to replace your "search" methods "Find_by_slug" (so that he (Not on the original ID)

  @ post = post.find_by_slug (params [: id])  

All this will give you a good URL ...

http://my_application.com/posts/my_post_about_flowers.html

This is a good


Comments

Popular posts from this blog

java - org.apache.http.ProtocolException: Target host is not specified -

java - Gradle dependencies: compile project by relative path -

ruby on rails - Object doesn't support #inspect when used with .include -