Rails 3.0.13,Devise,CanCan和ActiveScaffold; RVM上的Ruby 1.9.3 194(如果这有什么不同)
我正在尝试为设计用户和特定权限设置通用角色(要求是角色具有默认权限,但权限可以在用户级别覆盖)。 ability.rb能够使用is_implementer?
方法而不会出现问题
如果我进入控制台,将用户分配到var(@user
),然后执行@user.role
或@user.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的能力.rb)。
答案 0 :(得分:3)
执行不会获取数据并实例化用户的@user = User.where(:id => 2)
时。你的错误指出它是一个ActiveRecord :: Relation。
这是因为你可以做User.where(:active => true).limit(5)
因此,对于您的情况,您可以
@user = User.where(:id => 2).first
或
@user = User.find(2) # this is more common
然后你可以调用#role或#user_permissions,因为现在@user实际上是一个用户实例。