不使用主键查找帖子
要在我的控制器中获取某个帖子,您可以在我被要求创建的 URL 中输入类似的内容,
http://0.0.0.0:3000/post/1
http://0.0.0.0:3000/post/2
http://0.0.0.0:3000/post/3
这样就不能以这种方式获取它,而是使用随机字符串。例如,更像这样:
http://0.0.0.0:3000/post/wr4t-d2e2-1ee3
http://0.0.0.0:3000/post/prst-3r4t-1r1r
http://0.0.0.0:3000/post/asdo-2e12-sxas
问题 为了做到这一点,我应该在帖子表中创建另一个名为“令牌”或“随机”的列,并通过 find_by 使用该列来获取帖子吗?即 Post.find_by_token('wr4t-d2e2-1ee3') 关于
处理此问题的正确方法的任何意见。 我一直在阅读应用程序将使用'代理键'、'guid'、'自然键'、令牌的示例、随机
我只是对最佳实践有点不知所措。
To fetch a certain post in my controller you can type something like this in the URL
http://0.0.0.0:3000/post/1
http://0.0.0.0:3000/post/2
http://0.0.0.0:3000/post/3
I am being asked to make it so that it can't be fetched this way but with a random string. For example something more like this:
http://0.0.0.0:3000/post/wr4t-d2e2-1ee3
http://0.0.0.0:3000/post/prst-3r4t-1r1r
http://0.0.0.0:3000/post/asdo-2e12-sxas
Question
In order to do this should I create another column in the post table called 'token' or 'random' and use that column via find_by to fetch the post? i.e. Post.find_by_token('wr4t-d2e2-1ee3')
Any opinions on what is the right way to deal with this.
I have been reading up on examples where apps will use 'surrogate key', 'guid', 'natural key', token, random
I'm just a little overwhelmed on what the best practice is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找的是这样的:
Url's will generated as
然后您可以按照正常方式执行
您可以仅使用 before_validation 回调来生成令牌。
或者
您可以使用 gem 并使用 friend_id 它将为您处理此问题,并跟踪 slugs 的历史记录所生成的。不过,听起来这对于您的要求来说可能有点过分了。
What you are looking for is this:
Url's will generate as
Then you can do as per normal
You can generate your token by just using before_validation callback.
OR
You can go a gem and use friendly_id which will handle this for you, as well as track history of slugs that are generated. Tho, sounds like it it's probably overkill for your requirements.
您可能想检查Friendly_id gem。 https://github.com/norman/Friendly_id。
RailsCast: http://railscasts.com/episodes/314-pretty-urls-with -Friendlyid
您将需要一个
token
列,如果您使用 Devise,则可以使用Devise.Friendly_token
方法生成该列。You may want to check the friendly_id gem. https://github.com/norman/friendly_id.
RailsCast: http://railscasts.com/episodes/314-pretty-urls-with-friendlyid
You will need a
token
column which, if you are using Devise, can generate withDevise.friendly_token
method.