gpt4 book ai didi

ruby-on-rails - 如何使 ID 成为 Rails 中的随机 8 位字母数字?

转载 作者:数据小太阳 更新时间:2023-10-29 08:15:53 25 4
gpt4 key购买 nike

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

这是通过 API 发布到另一个第 3 方网站的 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

最佳答案

你只需要给post添加一个属性。属性名称是 permalink

尝试运行:

rails g migration add_permalink_to_posts permalink:string
rake db:migrate

你有两个 Active Record Callbacks您可以选择: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

最后,这里是 View (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 成为 Rails 中的随机 8 位字母数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16096511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com