user2159586 user2159586 -4 years ago 77
Ruby Question

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

Answer Source

You only need to add one attribute to post, attribute name is permalink

try run

rails g migration add_permalink_to_posts permalink:string
rake db:migrate

You can use Active Record Callbacks, you should make a choice between before_save or before_create and also you need know the difference from both. This example if using 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 permalink with random 8 digit alphanumeric
   self.permalink = SecureRandom.urlfsafe_base64(8)
 end

end

urlsafe_base64

And your routes.rb

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

on posts_controller.rb

def index
 @posts = Post.all
end

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

Finally, here's on views (index.html.erb) looks like :

<% @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 %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download