Users index
在列出所有使用者列表之前,我們要先實現安全機制(security model)。個人資料頁面(show page)對所有網站的訪客開放,但是使用者列表(index page)只開放給登入的使用者,未註冊的使用者則看不到。(Twitter 採用相同的作法)
為了限制瀏覽 index page 的動作,先寫一個簡短的測試,來檢查 index action 會正確導向:
test/controllers/users_controller_test.rb
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
def setup
@user = users(:michael)
@other_user = users(:archer)
end
test "should redirect index when not logged in" do
get :index
assert_redirected_to login_url
end
.
.
.
end
然後在 Users controller 增加 index action,並且把它放進 logged_in_user before filter 裡面:
app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update]
before_action :correct_user, only: [:edit, :update]
def index
end
def show
@user = User.find(params[:id])
end
.
.
.
end
為了要顯示所有使用者,我們要定義一個變數,儲存網站中的所有使用者,然後在 index action 中走訪每一位使用者,並呈現在 index view 裡面:
app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update]
.
.
.
def index
@users = User.all
end
.
.
.
end
接著建立 app/views/users/index.html.erb,顯示使用者的圖片和名稱:
app/views/users/index.html.erb
<% provide(:title, 'All users') %>
<h1>All users</h1>
<ul class="users">
<% @users.each do |user| %>
<li>
<%= gravatar_for user, size: 50 %>
<%= link_to user.name, user %>
</li>
<% end %>
</ul>
然後定義樣式:
app/assets/stylesheets/custom.css.sass
.
.
.
/* Users index */
.users
list-style: none
margin: 0
li
overflow: auto
padding: 10px 0
border-bottom: 1px solid $gray-lighter
最後在導覽列增加「Users」連結:
app/views/layouts/_header.html.erb
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<%= link_to "sample app", root_path, id: "logo" %>
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Help", help_path %></li>
<% if logged_in? %>
<li><%= link_to "Users", users_path %></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Account <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Profile", current_user %></li>
<li><%= link_to "Settings", edit_user_path(current_user) %></li>
<li class="divider"></li>
<li>
<%= link_to "Log out", logout_path, method: "delete" %>
</li>
</ul>
</li>
<% else %>
<li><%= link_to "Log in", login_path %></li>
<% end %>
</ul>
</nav>
</div>
</header>
執行測試會通過(Green):
$ bundle exec rake test
現在可以瀏覽使用者列表了 /users:
