문제

Rails 3.0.13, Devise, CanCan and ActiveScaffold; Ruby 1.9.3 194 on RVM (if that makes any difference)

I am trying to set up generic roles for the devise users and specific permissions (requirements are that roles have default permissions but the permissions can be overwritten at the user level). The ability.rb is able to use the is_implementer? method without issue

Keep getting this error for role or user_permissions if I go into console, assign a user to a var (@user) and then do @user.role or @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>'

Models:

User Class

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

User Permission

class UserPermission < ActiveRecord::Base
  belongs_to :user
  belongs_to :permission
end

Role

class Role < ActiveRecord::Base
  has_many :default_role_permission
  has_many :users

  def implementer?
    self.name == "Implementer"
  end
end

Let me know if you want to see anything else (e.g. CanCan's ability.rb).

도움이 되었습니까?

해결책

When you do @user = User.where(:id => 2) that does not fetch the data and instantiate the user. It's a ActiveRecord::Relation as your error points out.

THis is because you can do something like User.where(:active => true).limit(5)

So for your case you can do

@user = User.where(:id => 2).first 

or

@user = User.find(2) # this is more common

And then you can call #role or #user_permissions because now @user is really a User instance.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top