2013-05-06 44 views
1

對於我的rails應用程序,我試圖爲我的用戶創建一個隨機固定鏈接,以便它不是localhost:3000/users /:id,而是localhost:3000/users/permalink。Rails - 如何爲永久鏈接的用戶路由?

我按照崗位上做出了這裏: how to make ID a random 8 digit alphanumeric in rails?

繼後,我已經能夠創建爲我的用戶隨機永久鏈接欄和頁面,但一直沒能得到子頁面,工作。爲我的用戶,我現在有子頁面:關注等

問題:目前該頁面被路由到本地主機:3000 /用戶/ :id /追隨者等,但沒有人知道如何解決途徑。 RB,這樣我也可以使這些頁面爲localhost:3000 /用戶/ permalink /追隨者等

的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 

用戶/ _header.html.erb

<%= render 'users/followerstats' %> 

用戶/ _followerstats.html.erb

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

用戶/ 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> 
+0

永久性聽起來像它只是一個不同的ID。你爲什麼需要這個? – 2013-05-06 03:25:58

回答

1

我把它通過添加以下工作:

的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 

用戶/ _followerstats.html.erb

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

***** UPDATE:**基於@Benjamin辛克萊的建議

,並張貼在這裏(Best way to create unique token in Rails?),我定起來user.rb的make_it_permalink:

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 
0

好吧,你發現它,而我在寫:)

也請注意您的make_it_permalink功能。有2個用戶使用您的代碼獲得相同的永久鏈接的可能性很小。我建議你把它改爲:

def make_it_permalink 
    begin 
    self.permalink = SecureRandom.base64(8) 
    end while User.exists?(:permalink => self.permalink) 
end 
+0

我更新到你說的並得到錯誤:「ActiveRecord :: StatementInvalid,SQLite3 :: SQLException:no such column:users.Z1Vxcc9/GGY =:SELECT 1 AS one FROM」users「WHERE」users「。」Z1Vxcc9/GGY =「='Z1Vxcc9/GGY ='LIMIT 1」 – spl 2013-05-06 04:21:56

+0

感謝您的更新,我更新了我的代碼(第4行) – Benj 2013-05-09 02:50:04