2

Rails 3.0.13、Devise、CanCan 和 ActiveScaffold;RVM 上的 Ruby 1.9.3 194(如果有什么不同的话)

我正在尝试为设计用户和特定权限设置通用角色(要求角色具有默认权限,但可以在用户级别覆盖权限)。ability.rb 能够is_implementer?毫无问题地使用该方法

如果我进入控制台,将角色或 user_permissions 继续收到此错误,将用户分配给 var ( @user),然后执行@user.roleor @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),请告诉我。

4

1 回答 1

4

当您这样做时@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 实际上是一个用户实例。

于 2012-06-17T23:21:03.693 回答