ruby-on-rails – 如何在ID中将ID作为随机的8位字母数字?
发布时间:2020-12-16 20:52:54 所属栏目:百科 来源:网络整理
导读:这是我在模型中使用的东西 这是通过API发布到另一个第三方网站的URL 发布模型(post.rb) "#{content.truncate(200)}...more http://domain.com/post/#{id.to_s}" “id”指的是帖子ID.如何将其转换为随机的8位字母数字? 现在,它显示为人们可以改变的东西http:
这是我在模型中使用的东西
这是通过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 %> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |