Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

ruby - how to make ID a random 8 digit alphanumeric in rails?

This is something I am using inside my model

This is the URL that gets posted to another 3rd party website through API

Post Model (post.rb)

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

The "id" is referring to the post id. How can I convert that into a random 8 digit alphanumeric?

Right now, it gets displayed as something that people can alter http://domain.com/post/902

I want http://domain.com/post/9sd98asj

I know I probably need to use something like SecureRandom.urlsafe_base64(8) but where and how can I set this up?

This is what I have in routes.rb

match '/post/:id', :to => 'posts#show', via: :get, as: :post
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You only need to add one attribute to post. The attribute name is permalink.

Try running:

rails g migration add_permalink_to_posts permalink:string
rake db:migrate

You have twoActive Record Callbacks you can choose from: before_save or before_create (review the difference between both). This example is using the before_save callback.

note : for 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

And in your routes.rb file:

match "/post/:permalink" => 'posts#show', :as => "show_post"

In posts_controller.rb:

def index
 @posts = Post.all
end

def show
  @post = Post.find_by_permalink(params[:permalink])
end

Finally, here are the views (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 %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...