Rails - 如何为永久链接的用户路由?

时间:2013-05-06 03:23:34

标签: ruby-on-rails permalinks

对于我的rails应用程序,我正在尝试为我的用户创建一个随机永久链接,这样它就不是localhost:3000 / users /:id,而是localhost:3000 / users / permalink。

我已按照此处发布的帖子: how to make ID a random 8 digit alphanumeric in rails?

在帖子之后,我已经能够为我的用户创建随机永久链接列和页面,但是无法使子页面起作用。对于我的用户,我目前有子页面:关注者等。

问题:网页目前路由到localhost:3000 / users / :id /关注者等。但有人知道如何修复routes.rb以便我也可以路由这些页面为localhost:3000 / users / permalink / followers等。

的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>

2 个答案:

答案 0 :(得分: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 Sinclaire的建议并在此处发帖(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

答案 1 :(得分:0)

好的,你在我写作的时候找到了它。)

还要小心make_it_permalink功能。 2个用户与您的代码完全相同的可能性很小。我建议你把它改成:

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