Search code examples
ruby-on-railspermalinks

Rails - How to route for users with permalink?


For my rails application, I am trying to create a random permalink for my users so that it is not localhost:3000/users/:id, but rather, it is localhost:3000/users/permalink.

I have followed the post made here: how to make ID a random 8 digit alphanumeric in rails?

Following the post, I have been able to create the random permalink column and pages for my users, but have not been able to get the sub-pages to work. For my users, I currently have sub-pages: Followers, etc.

Question: The pages are currently routed to localhost:3000/users/:id/followers, etc. But does somebody know how to fix routes.rb so that I can also route these pages to localhost:3000/users/permalink/followers, etc.

routes.rb

match 'users/:permalink' => 'users#show', :as => "show_user"

resources :users do
  member do
    get :followers
  end
end

user.rb

attr_accessible :permalink

before_create :make_it_permalink

def make_it_permalink
  self.permalink = SecureRandom.base64(8)
end

users_controller.rb

def show
  @user = User.find_by_permalink(params[:permalink])
end

def followers
  @title = "Followers"
  @user = User.find(params[:id])
  @users = @user.followers.page(params[:page]).per_page(5)
  render 'show_follow'
end

users/_header.html.erb

<%= render 'users/followerstats' %>

users/_followerstats.html.erb

<a href = "<%= followers_user_path(@user) %>">
    My Followers ( <%= @user.followers.count %> )
</a>

users/show_follow.html.erb

<div class = "container">
  <%= render 'header' %>
  <% provide(:title, @title) %>
  <div class="row">
    <div class="span12"> 
      <h4><%= @title %></h4>
      <% if @users.any? %>
        <ul class="users">
          <%= render @users %>
        </ul>
        <%= will_paginate %>
      <% end %>
   /div>
</div>

Solution

  • I got it to work by adding the following:

    routes.rb

    match 'users/:permalink/followers' => 'users#followers', :as => "followers_user"
    

    users_controller.rb

    def followers
        @title = "Followers"
        @user = User.find_by_permalink(params[:permalink])
        @users = @user.followers.page(params[:page]).per_page(5)
        render 'show_follow'
    end
    

    users/_followerstats.html.erb

    <a href = "<%= followers_user_path(@user.permalink) %>">
       My Followers ( <%= @user.followers.count %> )
    </a>
    

    *****UPDATE:**

    Based on suggestion of @Benjamin Sinclaire and post here (Best way to create unique token in Rails?), I fixed up the make_it_permalink in user.rb:

    def make_it_permalink
        loop do
          # this can create permalink with random 8 digit alphanumeric
          self.permalink = SecureRandom.urlsafe_base64(8)
          break self.permalink unless User.where(permalink: self.permalink).exists?
        end
    end