Alain Goldman Alain Goldman - 2 months ago 22
Ruby Question

Rails - Making a page viewable to admin only

I have a super simple question. I have a page that lists all the products in my app. I just want to make that page view-able by admin only. But products/new I want everyone to be able to see clearly.

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


products controller

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

Answer

Put in your controller

before_filter :authorize_admin, only: :index

and in application_controller.rb

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