Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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中所拥有的

@H_591_6@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文件中:

@H_591_6@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 %>

大佬总结

以上是大佬教程为你收集整理的ruby-on-rails – 如何在ID中将ID作为随机的8位字母数字?全部内容,希望文章能够帮你解决ruby-on-rails – 如何在ID中将ID作为随机的8位字母数字?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。