ruby on rails分页的方法
There are several pagination methods in Rails; we’ll use one of the simplest and most robust, called will_paginate. To use it, we need to include both the will_paginate gem and bootstrap-will_paginate, which configures will_paginate to use Bootstrap’s pagination styles. The updated Gemfile appears in Listing 9.31.
在User的index.html.erb中加入
<% provide(:title, 'All users') %>
<h1>All users</h1>
<%= will_paginate %>
<ul class="users">
<% @users.each do |user| %>
<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
</li>
<% end %>
</ul>
<%= will_paginate %>
Using the paginate method, we can paginate the users in the sample application by using paginate in place of all in the index action (Listing 9.35). Here the :page parameter comes from params[:page], which is generated automatically by will_paginate.
def index @users = User.paginate(page: params[:page]) end以上是用来分页的。
admin?
The migration to add a boolean admin attribute to users.
db/migrate/[timestamp]_add_admin_to_users.rb
class AddAdminToUsers < ActiveRecord::Migration
def change
add_column :users, :admin, :boolean, default: false
end
end
由于admin这个属性不是attr_accessible 的,所以只能用以下类似代码
admin = User.create!(name: "Example User", email: "[email protected]", password: "foobar", password_confirmation: "foobar") admin.toggle!(:admin)
<li> <%= gravatar_for user, size: 52 %> <%= link_to user.name, user %> <% if current_user.admin? && !current_user?(user) %> | <%= link_to "delete", user, method: :delete, data: { confirm: "You sure?" } %> <% end %> </li>如果要delete一个用户,必须是admin或者是一个用户