如何在轨道中使ID成为随机的8位数字母数字?

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

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

发布模型(post.rb)

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

“id”指的是postID。 如何将其转换为随机的8位字母数字?

现在,它显示为人们可以改变的东西http://domain.com/post/902

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

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

这就是我在routes.rb中所拥有的

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

您只需添加一个属性即可post 。 属性名称是permalink

试试跑步:

 rails g migration add_permalink_to_posts permalink:string rake db:migrate 

您有两个Active Record Callback可供选择: before_savebefore_create (查看两者之间的差异)。 此示例使用before_save回调。

注意:对于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 ):

 <% @posts.each do |post| %> 

<%= truncate(post.content, :length => 300).html_safe %>

<%= link_to "Read More...", show_post_path(post.permalink) %>

<% end %>

“ 将Rails中的主键更改为字符串 ”与您的问题相关。

我会:

  • 在表上保留默认ID
  • 没有定义资源路由,用匹配编写所需的路由(比如match '/post/:code'
  • controller#show Post.find_by_code(params[:code]) ,使用Post.find_by_code(params[:code])