【问题标题】:how to make ID a random 8 digit alphanumeric in rails?如何使 ID 成为 Rails 中的随机 8 位字母数字?
【发布时间】:2013-04-12 08:50:14
【问题描述】:

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

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

【问题讨论】:

  • to_s 内插是多余的。
  • 如果你想要一个随机数,那么id是无关紧要的。
  • 如何在保持路径正常工作的同时用随机数替换 id?这是我在 routes.rb 中的内容:match '/post/:id', :to => 'posts#show', via: :get, as: :post

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

您只需向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

最后是观点(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 %>

【讨论】:

  • 不是使用视图显示最终链接,知道如何在模型中使用 URL 吗?这是我要放入模型而不是视图中的内容..."#{content.truncate(200)}...more http://domain.com/post/#{permalink}"
  • 这是我得到的错误undefined method 'permalink=' for #&lt;Post:0x55403a0&gt;
  • @user2159586,你需要把这个新字段添加到attr_accessible,你也需要先迁移。
  • @BillyChan,我明白了。所以我需要在 post 表中创建一个名为“permalink”的新列,并将其设为attr_accessible?
【解决方案2】:

Altering the primary key in Rails to be a string”与您的问题有关。

我愿意:

  • 在表格中保留默认 ID
  • 不定义资源路由,用匹配写入需要的路由(如match '/post/:code'
  • controller#show 上,使用Post.find_by_code(params[:code])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-29
    • 2021-04-05
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    相关资源
    最近更新 更多