ruby-on-rails – 如何在ID中将ID作为随机的8位字母数字?

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

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

发布模型(post.rb)

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

“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

解决方法

您只需添加一个属性即可发布.属性名称是永久链接.

试试跑步:

rails g migration add_permalink_to_posts permalink:string
rake db:migrate

您有两个Active Record Callbacks可以选择:before_save或before_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| %>
<p><%= truncate(post.content,:length => 300).html_safe %>
   <br/><br/>
   <%= link_to "Read More...",show_post_path(post.permalink) %></p>
<% end %>

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...