Ruby on rails 3 设计';的当前用户仅适用于管理员
我有一个标准的Ruby on rails 3 设计';的当前用户仅适用于管理员,ruby-on-rails-3,devise,cancan,Ruby On Rails 3,Devise,Cancan,我有一个标准的User模型,里面有一个adminboolean。对于设置为true的用户来说,这一切都很好,但对于普通用户,我会遇到以下错误: undefined local variable or method `current_user' app/models/doc.rb:18:in `mine' app/controllers/docs_controller.rb:9:in `index' 第18行的Doc模型如下所示: def self.mine where(:user_id =
User
模型,里面有一个admin
boolean。对于设置为true的用户来说,这一切都很好,但对于普通用户,我会遇到以下错误:
undefined local variable or method `current_user'
app/models/doc.rb:18:in `mine'
app/controllers/docs_controller.rb:9:in `index'
第18行的Doc
模型如下所示:
def self.mine
where(:user_id => current_user.name, :retired => "active").order('created_at DESC')
end
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
attr_accessor :current_password
attr_accessible :name, :password, :password_confirmation, :current_password, :email, :remember_me, :admin
end
class Ability
include CanCan::Ability
def initialize(user)
can :manage, :all if user.admin
end
end
我的用户
型号如下:
def self.mine
where(:user_id => current_user.name, :retired => "active").order('created_at DESC')
end
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
attr_accessor :current_password
attr_accessible :name, :password, :password_confirmation, :current_password, :email, :remember_me, :admin
end
class Ability
include CanCan::Ability
def initialize(user)
can :manage, :all if user.admin
end
end
class用户
在我的应用程序控制器中,我有以下内容:
class ApplicationController < ActionController::Base
protect_from_forgery
after_filter :user_activity
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_path
end
def admin?
self.admin == true
end
def authenticate_admin
redirect_to :new_user_session_path unless current_user && current_user.admin?
end
private
def user_activity
current_user.try :touch
end
end
class ApplicationController
我认为这是所有相关的事情。我一辈子都搞不清楚这一点。当前用户的帮助器是一种无法从模型访问的控制器方法。您应该将当前用户作为参数从控制器传递到模型
def self.mine(current_user)
where(:user_id => current_user.name, :retired => "active").order('created_at DESC')
end
编辑:旁注
看起来
user\u id
是逻辑中的一个字符串。如果这是你正在做的,你应该重新考虑。在数据库中使用标识符与rails建立一个“属于”和“拥有”的关系要容易维护得多。使用字符串ID是非常规的,它是一个兔子洞,在非常糟糕的地方结束。我认为在使用当前用户之前,您需要检查用户是否已登录。例如“如果登录?”。它在路由的索引方法中使用如果用户登录?
行进行检查。这非常有效!干杯您是否知道模型中命名范围中类似内容的语法,例如,scope:tagged_articles,lambda{tagged_with([current_user.billing,current_user.shadow],:any=>true)
?以及关于字符串的点。它很旧,但我仍然没有更改它。scope:mine,lambda{current_user | where(:user_id=>current_user.name,:retired=>“active”).order('created_at DESC')}
非常感谢您的帮助。