Search code examples
ruby-on-railscancanrolify

Rolify with_all_roles not working if User model has resource defined


I want to get a list of say moderators from User model, it works in this case

u = User.new(:name => "n", :surname => "s", :email => "a@m.c", :password => "x")
u.add_role(:moderator)
u.save!

but if i assign a resource to User model like this, it's not listing users with role moderator

u = User.new(:name => "m", :surname => "b", :email => "a@m.c", :password => "x")
u.add_role(:moderator, Post.first)
u.save!

UPDATE

post.rb

class Post < ActiveRecord::Base
  attr_accessible :user_id, :content
  belongs_to :user
end

user.rb

class User < ActiveRecord::Base
  rolify
end

Solution

  • You should add resourcify to your Post model and other all models you want to apply roles on, as described in readme.

    So, your Post model should look like:

    Post.rb

    class Post < ActiveRecord::Base
      resourcify
      attr_accessible :user_id, :content
      belongs_to :user
    end
    

    * EDIT *

    You can get all users with role :admin using User.with_all_roles({:name => :admin})

    I've created a vanilla project uses rolify with same User and Post model. Change Post model and add resourcify, change User model and add has_many :posts

    user = User.create(...)
    user.add_role :admin
    post = user.posts.create(...)
    user2 = User.create(...)
    user2.add_role(:moderator, post)
    

    Seems working with these:

    • User.with_all_roles({:name => :admin})
    • User.with_all_roles({:name => :moderator, :resource => Post })
    • User.with_all_roles({:name => :moderator, :resource => Post.first })