[英]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 ...). 我们如何获得Active Record来创建更复杂的ID,而不仅仅是自然数(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.
我不确定是否应该使用数据库ID来标识对象,但是现在,要在生产环境中使用这样的对象将是非常不安全的。
Lets just say you want to use a column called slug
for an object called Post
. 假设您要对名为
Post
的对象使用称为slug
的列。
slug
column for that table slug
列 before_create
method in Post
model that will generate a unique slug
value before saving the record. before_create
的方法Post
模型,将生成一个唯一的slug
保存记录之前的值。 Maybe do some checking to ensure it's unique Post.find_by(slug: id)
instead of Post.find(id)
. Post.find_by(slug: id)
代替Post.find(id)
。 post_path(id: post.slug)
so that it won't put the id
the URL. post_path(id: post.slug)
将使用以下内容: post_path(id: post.slug)
以便不会将id
放在URL中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.