Rails 3.0.13, Devise, CanCan and ActiveScaffold;RVM 上的 Ruby 1.9.3 194(如果这有什么不同的话)
我正在尝试为设计用户和特定权限设置通用角色(要求是角色具有默认权限,但可以在用户级别覆盖权限)。ability.rb 能够毫无问题地使用 is_implementer?
方法
如果我进入控制台,将用户分配给 var ( @user
),然后执行@user.role
或@user.user_permissions
,则不断收到角色或user_permissions此错误:
NoMethodError: undefined method `role' for #<ActiveRecord::Relation:0x98173e8>
from /home/scott/.rvm/gems/ruby-1.9.3-p194@rails3/gems/activerecord-3.0.13/lib/active_record/relation.rb:374:in `method_missing'
from (irb):7
from /home/scott/.rvm/gems/ruby-1.9.3-p194@rails3/gems/railties-3.0.13/lib/rails/commands/console.rb:44:in `start'
from /home/scott/.rvm/gems/ruby-1.9.3-p194@rails3/gems/railties-3.0.13/lib/rails/commands/console.rb:8:in `start'
from /home/scott/.rvm/gems/ruby-1.9.3-p194@rails3/gems/railties-3.0.13/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
模型:
用户类
class User < ActiveRecord::Base
has_and_belongs_to_many :user_groups
has_many :user_permissions
belongs_to :role
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :role_id
def is_implementer?
self.role.implementer?
end
end
用户权限
class UserPermission < ActiveRecord::Base
belongs_to :user
belongs_to :permission
end
角色
class Role < ActiveRecord::Base
has_many :default_role_permission
has_many :users
def implementer?
self.name == "Implementer"
end
end
如果您想查看其他内容(例如CanCan的ability.rb),请告诉我。
当你这样做时@user = User.where(:id => 2)
不会获取数据并实例化用户。这是一个活动记录::关系,正如你的错误所指出的那样。
这是因为你可以做类似User.where(:active => true).limit(5)
的事情
所以对于你的情况,你可以做
@user = User.where(:id => 2).first
或
@user = User.find(2) # this is more common
然后你可以调用 #role 或#user_permissions,因为现在@user实际上是一个用户实例。