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

use*_*586 2 ruby ruby-on-rails ruby-on-rails-3

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

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

发布模型(post.rb)

"#{content.truncate(200)}...more http://domain.com/post/#{id.to_s}"
Run Code Online (Sandbox Code Playgroud)

"id"指的是帖子ID.如何将其转换为随机的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
Run Code Online (Sandbox Code Playgroud)

rai*_*_id 10

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

试试跑步:

rails g migration add_permalink_to_posts permalink:string
rake db:migrate
Run Code Online (Sandbox Code Playgroud)

您有两个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
Run Code Online (Sandbox Code Playgroud)

urlsafe_base64

在您的routes.rb文件中:

match "/post/:permalink" => 'posts#show', :as => "show_post"
Run Code Online (Sandbox Code Playgroud)

posts_controller.rb:

def index
 @posts = Post.all
end

def show
  @post = Post.find_by_permalink(params[:permalink])
end
Run Code Online (Sandbox Code Playgroud)

最后,这里是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 %>
Run Code Online (Sandbox Code Playgroud)