加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails – 使页面只能被管理员查看

发布时间:2020-12-17 01:47:14 所属栏目:百科 来源:网络整理
导读:我有一个非常简单的问题.我有一个页面列出了我的应用程序中的所有产品.我只想让管理员只查看该页面.但产品/新产品我希望每个人都能清楚地看到. schema.rb create_table "users",:force = true do |t| t.string "email" t.string "password_hash" t.string "p
我有一个非常简单的问题.我有一个页面列出了我的应用程序中的所有产品.我只想让管理员只查看该页面.但产品/新产品我希望每个人都能清楚地看到.

schema.rb

create_table "users",:force => true do |t|
    t.string   "email"
    t.string   "password_hash"
    t.string   "password_salt"
    t.datetime "created_at",:null => false
    t.datetime "updated_at",:null => false
    t.string   "name"
    t.boolean  "admin",:default => false
  end

产品控制器

class ProductsController < ApplicationController
    before_filter :require_login
    before_filter :current_user,only: [:create,:destory]
    before_filter :correct_user,only: :destory

  def index
    @products = Product.all
  end

  def new 
    @product = Product.new
  end

  def create
  @product = current_user.products.new(params[:product])
    if @product.valid? 
      @product.save
        render "show",:notice => "Sale created!"
    else
        render "new",:notice => "Somehting went wrong!"
    end
end

解决方法

放入你的控制器

before_filter :authorize_admin,only: :index

并在application_controller.rb中

def authorize_admin
    redirect_to :back,status: 401 unless current_user.admin
    #redirects to previous page
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读