【问题标题】:Display an Index of Admin Users in Ruby on Rails在 Ruby on Rails 中显示管理员用户的索引
【发布时间】:2012-04-20 05:36:57
【问题描述】:

我已经完成了 Michael Hartl Ruby on Rails 教程(适用于 Rails 3),我想知道您将如何显示所有已分配 Admin 属性但在单独页面上的用户,因为它没有提及这在任何地方。

users_controller.rb

    class UsersController < ApplicationController
  before_filter :authenticate, :only => [:index, :edit, :update, :destroy]
  before_filter :correct_user, :only => [:edit, :update]
  before_filter :admin_user,   :only => :destroy

  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(:page => params[:page])
    @title = @user.name
  end

  def new
    @user = User.new
    @title = "Sign up"
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      sign_in @user
      flash[:success] = "Welcome to University Sports!"
      redirect_to @user
    else
      @title = "Sign up"
      render 'new'
    end
  end

  def edit
    @title = "Edit user"
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated."
      redirect_to @user
    else
      @title = "Edit user"
      render 'edit'
    end
  end

  def index
    @users = User.paginate(:page => params[:page])
  end

  def admins
    @users = User.admins
    render "users/index"
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User destroyed."
    redirect_to users_path
  end

  def following
    @title = "Following"
    @user = User.find(params[:id])
    @users = @user.following.paginate(:page => params[:page])
    render 'show_follow'
  end

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

  private

    def authenticate
      deny_access unless signed_in?
    end

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_path) unless current_user.admin?
    end

end

Routes.rb

FinalProject::Application.routes.draw do
  get "club/new"

  resources :users do
    member do
      get :following, :followers
    end
  end

  resources :users do
    collection do
      get :admins
    end
  end

  resources :sessions, :only => [:new, :create, :destroy]
  resources :microposts, :only => [:create, :destroy]
  resources :relationships, :only => [:create, :destroy]
  get "sessions/new"

  match '/signup',  :to => 'users#new'
  match '/signin',  :to => 'sessions#new'
  match '/signout', :to => 'sessions#destroy'

  match '/sign_up', :to => 'pages#sign_up'

  root :to => 'pages#home'

  resources :users
  match '/signup',  :to => 'users#new'

end

user.rb

class User < ActiveRecord::Base
    attr_accessor :password
    attr_accessible :name, :email, :password, :password_confirmation

    has_many :microposts, :dependent => :destroy
    has_many :relationships, :foreign_key => "follower_id", :dependent => :destroy
    has_many :following, :through => :relationships, :source => :followed   
    has_many :reverse_relationships, :foreign_key => "followed_id", :class_name => "Relationship", :dependent => :destroy
    has_many :followers, :through => :reverse_relationships, :source => :follower

    email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

    validates :name,    :presence   => true, :length  => { :maximum => 50 }
    validates :email,   :presence   => true, :format  => { :with => email_regex }, :uniqueness => { :case_sensitive => false }

    scope :admins, where(:admin => true)

    # Automatically create the virtual attribute 'password_confirmation'.
    validates :password, :presence  => true, :confirmation  => true, :length  => { :within => 6..40 }
        before_save :encrypt_password

  def has_password?(submitted_password)
    encrypted_password == encrypt(submitted_password)
  end

  def self.authenticate(email, submitted_password)
    user = find_by_email(email)
    return nil  if user.nil?
    return user if user.has_password?(submitted_password)
  end

  def self.authenticate_with_salt(id, cookie_salt)
    user = find_by_id(id)
    (user && user.salt == cookie_salt) ? user : nil
  end

  def following?(followed)
    relationships.find_by_followed_id(followed)
  end

  def follow!(followed)
    relationships.create!(:followed_id => followed.id)
  end

  def unfollow!(followed)
    relationships.find_by_followed_id(followed).destroy
  end

  def feed
    Micropost.from_users_followed_by(self)
  end

  private

    def encrypt_password
      self.salt = make_salt unless has_password?(password)
      self.encrypted_password = encrypt(password)
    end

    def encrypt(string)
      secure_hash("#{salt}--#{string}")
    end

    def make_salt
      secure_hash("#{Time.now.utc}--#{password}")
    end

    def secure_hash(string)
      Digest::SHA2.hexdigest(string)
    end



end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    首先,您需要在config/routes.rb 文件中创建一个路由,该路由将路由到显示此信息的操作。像这样的:

    resources :users do
      collection do
        get :admins
      end
    end
    

    这将路由到UsersController 中的admins 操作,这就是您接下来需要定义的内容。它会是这样的:

    def admins
      @users = User.admins
      render "users/index"
    end
    

    因为管理员列表不应与用户列表相差太大,您可以将所有管理员分配给@users,然后渲染users/index 模板...如果存在。我可能在这里假设太多,但这是一种方法。

    现在,您的 User 类上没有 admins 方法,因此您需要定义它。一种方法是使用范围,如下所示:

    scope :admins, where(:admin => true)
    

    这将在User 类上定义admins 方法,返回所有管理员用户的范围。范围很酷,你应该看看它们还能做什么。

    或者,您可以定义一个类方法:

    def self.admins
      where(:admin => true)
    end
    

    【讨论】:

    • 我有点困惑,我已经完成了您上面推荐的所有操作,并且在 app/views/users 中确实有文件 index.html.erb。我尝试添加 但它在 Users#index 中产生了 NoMethodError 所以我将其删除。
    • 你为什么要输入&lt;%= render @admins %&gt;?您将其分配给 @users 变量并引用您现有的 Users#index 模板。您应该能够调用 /users/admins 并让它工作。
    【解决方案2】:

    您应该执行以下操作:

    UsersController
    
    def admins
       @admins=User.where(:admin => true)
    end
    

    并将其添加到您的路线文件中:

     resources :users do
        collection do
          get :admins
        end
     end
    

    然后只需在 admins.html.erb 视图中呈现 @admins 实例变量(您将在用户视图中创建它)。

    【讨论】:

    • 我已经尝试过了,但它出现了错误“ActiveRecord::RecordNotFound in UsersController#show”并且应用程序跟踪显示“app/controllers/users_controller.rb:7:in 'show '" 我尝试将 def 显示更新为以下 def show @user = User.find(params[:id]) @microposts = @user.microposts.paginate(:page =&gt; params[:page]) @title = @user.name @admins = User.find(params[:id]) end
    • 处理 ActiveRecord 的最佳方法是使用 rails 控制台来获得有关查询的即时反馈。试试 'admins=User.where(:admin => "true") 你会得到一个包含所有符合你条件的对象的数组。至于您的 admins 实例变量,它应该是 @admins=User.where(:admin => true) 而不是 @admins = User.find(params[:id])
    猜你喜欢
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多