В данный момент я создаю некую админ-панель / бэкэнд для своего сайта.
Я хочу сделать следующее:
Только администраторы (пользователь имеет user_role (целое число) -> 1 = администратор, 2 = модератор, 3 = пользователь) могут видеть и получать доступ к ссылке для панели администратора.
Поэтому я создал admin_controller. В моем контроллере администратора я создал новую функцию с именем is_admin?:
class AdminController < ApplicationController
def admin_panel
end
def is_admin?
current_user.user_role == 1
end
end
мой маршрут выглядит так.
map.admin_panel '/admin-panel', :controller => 'admin', :action => 'admin_panel'
и в моем _sidebar.html.erb (частично в Applicaton.html.erb) я создал ссылку:
<%= link_to "Admin Panel", :admin_panel unless is_admin? %>
Теперь я получаю сообщение об ошибке:
undefined method `is_admin?'
Где проблема? Пожалуйста, помогите мне решить эту проблему!
Хорошо, извините за это, но это все равно не сработает. Вот мои контроллеры:
application_controller.rb:
class ApplicationController < ActionController::Base
include AuthenticatedSystem
helper :all
protect_from_forgery
helper_method :current_user
def current_user
@current_user ||= User.find_by_id(session[:user])
end
end
users_controller.rb:
class UsersController < ApplicationController
layout 'application'
include AuthenticatedSystem
helper_method :is_admin? #only added this line
def new
end
...
end
user.rb
require 'digest/sha1'
class User < ActiveRecord::Base
# Virtual attribute for the unencrypted password
attr_accessor :password
... #more stuff but nothing for is_admin?
def active?
# the existence of an activation code means they have not activated yet
activation_code.nil?
end
#here is my is_admin? code
def is_admin?
self.user_role == 1
end
...
end
и теперь мой взгляд (_sidebar.html.erb):
<div>
<%= link_to "Admin Panel", :admin_panel unless current_user.is_admin? %>
</div>
Вот и все. Есть идеи?
Кстати: теперь ошибка немного изменилась. Теперь это:
undefined method `is_admin?' for nil:NilClass
Создание моей сессии (в session_controller.rb):
def create
self.current_user = User.authenticate(params[:login], params[:password])
if logged_in?
if params[:remember_me] == "1"
current_user.remember_me unless current_user.remember_token?
cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
end
redirect_back_or_default('/')
flash[:notice] = "Logged in successfully"
else
render :action => 'new'
end
конец