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

后端 未结 2 1388
Happy的楠姐
Happy的楠姐 2020-12-18 13:58

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)

\         


        
相关标签:
2条回答
  • 2020-12-18 14:35

    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 %>
    
    0 讨论(0)
  • 2020-12-18 14:41

    "Altering the primary key in Rails to be a string" is related to your question.

    I would:

    • Leave default ID on table
    • Not define resources routes, writing the needed ones with match (like match '/post/:code')
    • On controller#show, use Post.find_by_code(params[:code]).
    0 讨论(0)
提交回复
热议问题