如何在rails中使ID成为随机的8位字母数字? [英] how to make ID a random 8 digit alphanumeric in rails?

查看:29
本文介绍了如何在rails中使ID成为随机的8位字母数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在模型中使用的东西

This is something I am using inside my model

这是通过 API 发布到另一个 3rd 方网站的 URL

This is the URL that gets posted to another 3rd party website through API

发布模型(post.rb)

Post Model (post.rb)

"#{content.truncate(200)}...more http://domain.com/post/#{id.to_s}"

id"指的是帖子 ID.如何将其转换为随机的 8 位字母数字?

The "id" is referring to the post id. How can I convert that into a random 8 digit alphanumeric?

现在,它显示为人们可以更改的内容http://domain.com/post/902

Right now, it gets displayed as something that people can alter http://domain.com/post/902

我想要http://domain.com/post/9sd98asj

我知道我可能需要使用诸如 SecureRandom.urlsafe_base64(8) 之类的东西,但是我在哪里以及如何设置它?

I know I probably need to use something like SecureRandom.urlsafe_base64(8) but where and how can I set this up?

这是我在 routes.rb 中的内容

This is what I have in routes.rb

match '/post/:id', :to => 'posts#show', via: :get, as: :post

推荐答案

您只需要在 post 中添加一个属性.属性名称是 permalink.

You only need to add one attribute to post. The attribute name is permalink.

尝试运行:

rails g migration add_permalink_to_posts permalink:string
rake db:migrate

您有两个活动记录回调可以选择:before_savebefore_create(查看两者的区别).此示例使用 before_save 回调.

You have twoActive Record Callbacks you can choose from: before_save or before_create (review the difference between both). This example is using the before_save callback.

注意:对于 Rails 3.x

class Post < ActiveRecord::Base
  attr_accessible :content, :permalink
  before_save :make_it_permalink

 def make_it_permalink
   # this can create a permalink using a random 8-digit alphanumeric
   self.permalink = SecureRandom.urlsafe_base64(8)
 end

end

urlsafe_base64

在你的 routes.rb 文件中:

match "/post/:permalink" => 'posts#show', :as => "show_post"

posts_controller.rb 中:

def index
 @posts = Post.all
end

def show
  @post = Post.find_by_permalink(params[:permalink])
end

最后,这里是视图(index.html.erb):

Finally, here are the views (index.html.erb):

<% @posts.each do |post| %>
<p><%= truncate(post.content, :length => 300).html_safe %>
   <br/><br/>
   <%= link_to "Read More...", show_post_path(post.permalink) %></p>
<% end %>

这篇关于如何在rails中使ID成为随机的8位字母数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆